$(function () {
    //ajax setup
    $.ajaxSetup({ cache: false, dataType: "html" });

    //load ajax mailing
    if ($('#ajaxmailing').length > 0 && $('#ajaxmailing').html() == '&nbsp;') {
        ajaxMailing(1, '');
    }

});

//submit login form
function onLoginClick() {
    $('#loginform').submit();
}

// show content image popup
function showAjaxLargeImage(position, contenttypeid, contentid) {

    //set window width and height
    $('#modalwindow').css({ width: 687, height:350 });
    $('#modalwindow').addClass('modalwindowlargeimage');

    //call ajax
    $.ajax({
        url: 'http://help.buyitc.si/ajaxlargeimage.aspx',
        data: ({ position: position, contenttypeid: contenttypeid, contentid: contentid }),
        success: function (data) {

            $('#modalwindow').html(data);
            openPopup();

            $('#largeimage').hide();
            $('#largeimage').fadeIn(2000);
        }
    });
}

/* POPUP */
function showPopup(contentdivid) {

    //show popup send sendPassword
    if (contentdivid == "sendPassword") {
        $("#sendPassword").css("display", "block");
        $("#forwardMail").css("display", "none");
        $("#preparingPdfBooklet").css("display", "none");
        $("#finishedPdfBooklet").css("display", "none");

        $("#sendPassword .successful").html("");
        $("#sendPassword .successful").css("display", "none");
        $("#sendPassword .content").css("display", "block");
    }
    //show popup send forwardMail
    else if (contentdivid == "forwardMail") {
        $("#sendPassword").css("display", "none");
        $("#preparingPdfBooklet").css("display", "none");
        $("#finishedPdfBooklet").css("display", "none");
        $("#forwardMail").css("display", "block");        

        $("#subject").html($("#title-subject").html());

        $("#forwardMail .numchartitle").css("display", "none");

        $("#forwardMail .successful").html("");
        $("#forwardMail .successful").css("display", "none");
        $("#forwardMail .content").css("display", "block");
    }
 
    else if("preparingPdfBooklet") {//show pdf booklet preparing

        var counter = 0;

        //loop through all checkboxes
        $("input:checked").each(function (index, domEle) {
            counter++;
        });

        if (counter > 0) {
                   
            $("#ajaxLoadGifDiv .ajaxLoadGif").css("display", "block");
        }

    }

    openPopup();
}

//0 = disabled; 1 = enabled;  
var popupStatus = 0;

//open popup
function openPopup() {
    if (popupStatus == 0) {
        //set that popup is open
        popupStatus = 1;

        //check for IE - show modal window
        if ($.browser.msie) {
            $('#modalwindowbackground').css({ 'opacity': '0.0' });
            $('#modalwindowbackground').css('display', 'block');
            $('#modalwindow').css('display', 'block');
        }
        else {
            $('#modalwindowbackground').css({ 'opacity': '0.0' });
            $('#modalwindowbackground').fadeIn('fast');
            $('#modalwindow').fadeIn('fast');
        }

        //popup - center
        centerPopup();
    }
}

//position popup in center of window
function centerPopup() {
    //request data for centering
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    var popupWidth = $("#modalwindow").width();
    var popupHeight = $("#modalwindow").height();

    var newWidth = windowHeight / 2 - popupHeight / 2;
    var newHeight = windowWidth / 2 - popupWidth / 2;

    //centering
    $('#modalwindow').css({ top: newWidth - 70, left: newHeight });
}

//dispose popup
function disposePopup() {
    //disables popup only if it is enabled
    if (popupStatus == 1) {
        //mozilla
        if ($.browser == "mozilla" && $.browser.version.substr(0, 3) == "1.9") {
            $('#modalwindowbackground').fadeOut('fast');
            $('#modalwindow').fadeOut('fast');
            $('#adseldiv').fadeOut('fast');
        } else {
            $('#modalwindowbackground').css('display', 'none');
            $('#modalwindow').css('display', 'none');
            $('#adseldiv').css('display', 'none');
        }

        //set that popup is closed
        popupStatus = 0;
    }
}

//close popup window
function closePopup() {
    //popup - dispose
    disposePopup();
    
    var manualpdfbookletid = $("#manualpdfbookletid").val();  

    //if pdfbooklet id exist reload page on close popup
    if($('#manualpdfbookletid').length > 0 && manualpdfbookletid != "0" && manualpdfbookletid != "")
    {
        var sURL = unescape(window.location.pathname);
        window.location.href = sURL;
    }
}

/* CONTENT, LOCATION */

//show selected item icon
function showSelector(docid) {

    $('#selector_' + docid).show();
}

//hide selected item icon
function hideSelector(docid) {
    $('#selector_' + docid).hide();
}

//show modulepopup
function showModulePopup(docid) {

    //hide all popups
    $('.modulepopup').hide();

    //get icon position
    var pos = $('#moduleimage_' + docid).position();    

    //move popup over icon
    $('#modulepopup_' + docid).css({ "left": (pos.left) + "px", "top": pos.top + "px" });    
    
    //show popup
    $('#modulepopup_' + docid).show();
}

//show modulepopup
function hideModulePopup(docid) {
    //hide all popups
    $('.modulepopup').hide();
}


/* SOLUTIONS.ASPX */
var popup_shown = "";

//show solution popup
function showSolutionPopup(docid) {
    $('#solutionpopup_' + docid).show();    
}

//hide solution popup
function hideSolutionPopup(docid) {
    $('#solutionpopup_' + docid).hide();    
}

/* SEARCH.ASPX */
//set search page
function setSearchPage(page) {
    $('#page').val(page);
    $('#sitesearchform').submit();
}

//show upper contact box (popup)
function showContactBox() {
    $('#box-open').show();
}

//hide upper contact box (popup)
function hideContactBox() {
    $('#box-open').hide();
}

//send password
function sendPassword() {

    var emailOrUsername = $('#emailOrUsername').val();  //input value

    $(".ajaxLoadGif ").fadeIn("fast");   //show ajax loader    

    //ajax post
    $.post('http://help.buyitc.si/ajaxsendpassword.aspx', { emailorusername: emailOrUsername },
        function (data) {

            $(".ajaxLoadGif").css("display", "none");   //hide ajax loader
            $("#sendPassword .successful").html(data);  //
            $("#sendPassword .successful").css("display", "block");
            $("#sendPassword .content").css("display", "none");

            $("#emailOrUsername").val("");
            
        });
    }

//validate email
function validateEmail(email) 
{
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return email.match(re); 
}

// forward message
function forwardMessage() {

    var email = $('#messageEmail').val();
    var messageBody = $('#messageBody').val();
    var url = $('#currentPageUrl').val();
    var subject = $("#subject").html();

    //validate email
    if (validateEmail(email) == null) {
        $("#forwardMail .emailnotexist").css("display", "block");   //show message
    }
    else {
        $("#forwardMail .emailnotexist").css("display", "none");    //hide message
    }     

    // if number of chars less then 3 disply error message
    if (messageBody.length < 3) {
        $("#forwardMail .numchartitle").css("display", "block");    //show message
        return;
    }

    $("#forwardMail .ajaxLoadGif ").fadeIn("fast");   //show ajax loader
    
    //if email and message body not empty
    if (email != "" && messageBody != "") {

        //post email data
        $.post('http://help.buyitc.si/ajaxforwardmessage.aspx', { subject: subject, email: email, messagebody: messageBody, url: url },
            function (data) {
                $("#forwardMail .successful").html(data);   //fill div with data (message successfull send)
                $("#forwardMail .successful").css("display", "block");  //show message
                $("#forwardMail .content").css("display", "none");      //hide message
                $("#forwardMail .emailnotexist").css("display", "none");    //hide message

                //empty input values
                $("#messageEmail").val("");
                $("#messageBody").val("");

                $(".ajaxLoadGif").css("display", "none");   //hide ajax loader

            });
        }
}

//executes on message email change
function messageBodyChange(e) {

    ///message body must have content
    if ($("#messageBody").val().length > 0) {
        $("#forwardMail .numchartitle").css("display", "none");
    }
    else { //if message body doesn't exist display warrning
        $("#forwardMail .numchartitle").css("display", "block");
    }
}

//on message body focus
function onMessageBodyFocus() {
    //if message body contains only spacer   
    if ($("#messageBody").val().length <= 1) {
        $("#messageBody").val(''); //empty textarea        
    }
}

//open menu more
function popUpMore() {

    //hide all dropdown menus
    $("div[id*='dropwdown_']").slideUp("fast");

    //if dropdown menu "more" is visible then hide it
    if ($("#popup-more").is(":visible")) {        
        $("#popup-more").slideUp("fast");
    }
    else { //show dropdown menu "more"
        $("#popup-more").slideDown("fast");
    }
}

//opean drop down menu of main menu - 2. level
function dropDown(nodeid) {

    // hide other opened menus
    $("div[id*='dropwdown_']").slideUp("fast");
    $("#popup-more").slideUp("fast");    
    
    //if dropdown menu opened
    if ($("#dropwdown_" + nodeid).is(":visible")) {        
        $("#dropwdown_" + nodeid).slideUp("fast");
    }
    else {//if dropdown menu closed        
        $("#dropwdown_" + nodeid).slideDown("fast");
    }
}

// load sub navigation
function ajaxNavigationSub(nodeid, parentnodeid, clicked) {
    //close all opened menus
    dropDown(nodeid);   
    //return sub navigation
    postData(nodeid, 0, 0);
}

//return subnavigation
function postData(nodeid, parentnodeid, clicked) {

    var uri = $("#hiddenuri").val();    //page uri

    $("#ajaxLoadGif").fadeIn("fast");   //show ajax loader
    
    //ajax post
    $.post('http://help.buyitc.si/ajaxnavigationsub.aspx', { nodeid: nodeid, uri: uri },   

    function (data) {
        if (data.length > 1) {  // if data exist
            $("#ajaxLoadGif").css("display", "none"); //hide ajax loader
            $("#navigationsub").html(data); // load data into div with id="navigationsub"            
        }
    });
}

//show or hides child nodes
function showHideNode(nodeid) {
    if ($("#ul_" + nodeid).is(":visible")) {
        $("#ul_" + nodeid).slideUp("fast");
    }
    else {
        $("#ul_" + nodeid).slideDown("fast");
    }
}

//scroll to the top of page
function scrollTop() {
     $('html, body').animate({scrollTop: '0px'}, 800);

 }
//show or hide to the top link
 function showHideLinkToTop() {
    var height = $(window).height();  //get the borwser window height   
    
    var bodyOffset = document.getElementById('maincontent').offsetHeight; // get document body offset    

    //hide link to the top
    if (height - bodyOffset > 0) {
        $("#linktothetop").css("display", "none");
    }
    else {  //show link
        $("#linktothetop").css("display", "block");
    }
}

//check or uncheck nodes
function onCheckBoxChecked(currentClass) {

    //id of current clicked node
    var currentClicked = '';
    
    //loop through all checkboxes
    $("input[id*='chk_']").each(function () {

        //id of current clicked node
        currentClicked = "chk_" + currentClass;

        //check if checkbox id contains current id and currently clicked is different than current
        if (this.id.indexOf("chk_" + currentClass) == 0 && currentClicked != this.id) {

            //if parent node already checked
            if ($("#" + currentClicked).is(":checked")) {
                $('#' + this.id).attr("checked", true);    //check it               
            }
            //if parent node not selected, uncheck all child nodes
            else {
                $('#' + this.id).attr("checked", false);   //unckeck it
            }
        }

    });
    
}

//searches for selected checkboxes
function getSelectedChkBoxes() {

    var sSelectedNodesTitles = "";  //contains selected nodes titles
    var sSelectedNodes = "";    //contains selected nodes ids   

    //loop through all checkboxes
    $("input:checked").each(function (index, domEle) {
    
        if (sSelectedNodesTitles == "") {
            sSelectedNodesTitles = this.value;          //extract checkbox value
            sSelectedNodes = this.name;  //extract checkbox name            
        }
        else {
            sSelectedNodesTitles += ", " + this.value;          //extract checkbox value
            sSelectedNodes += "," + this.name;  //extract checkbox name
        }
    });

    //set value to hidden input selectedNodes
    $("#nodeids").val(sSelectedNodes);
    //set value to hidden input contentTree
    $("#contentTree").html(sSelectedNodesTitles);    

}

//login input onkeypress event
function onLogin(event) {

    //if enter key pressed
    if (event.keyCode == 13){
        onLoginClick();
     }
}

//open link in new window
$(function () {
  
    //facebooklink
    $('#hreffacebook').click(function () {
        window.open(this.href);
        return false;
    });

    //facebooklink
    $('#hreffbblank').click(function () {
        window.open(this.href);
        return false;
    });

    //news images
    $("[id*='newsImage_']").click(function () {
        window.open(this.href);
        return false;
    });

    //new link more
    $("#hrefNewsMore").click(function () {
        window.open(this.href);
        return false;
    });

    //new link more
    $("#referencesLink").click(function () {
        window.open(this.href);
        return false;
    });

    //pdf icon
    $("#hrefPdfIcon").click(function () {
        window.open(this.href);
        return false;
    });

});

//id of refresh interval
var refreshIntervalId;

//checks if generating booklet already finished
function checkPdfBookletFinished(manualpdfbookletid) {    
    
    //ajax post
    $.post('http://help.buyitc.si/ajaxpdfbookletfinished.aspx', { manualpdfbookletid: manualpdfbookletid, clearsession: 0 },

    function (data) {
        //if finished
        if (data.indexOf("notfinished") == -1) {
            $("#finishedPdfBooklet .finishedPdfBookletContent").html(data); // load data into popup  

            //hide popup preparing booklet
            $("#preparingPdfBooklet").css("display", "none");
            //hide ajax loader
            $("#ajaxLoadGifDiv .ajaxLoadGif").css("display", "none");
            //show popup 
            $("#finishedPdfBooklet").css("display", "block");
            $("#finishedPdfBooklet").css("display", "block");
            openPopup();

            //clear interval
            clearInterval(refreshIntervalId);
        }
    });
}
//checks if at least one node is selected
function checkNodeSelected() {
    //node checked
    var checked = false;

    //check if title entered
    if ($("#bookletTitle").val().length == 0) {
        $(".pdfBookletTitleValidator").css("display", "block");   //show error message
        $(".pdfBookletValidator").css("display", "none");   //hide error message
        return false;
    }
    else {
        $(".pdfBookletTitleValidator").css("display", "none");   //hide error message        
    }

    //loop through all checkboxes
    $("input[id*='chk_']").each(function () {
        //if node checked     
        if ($('#' + this.id).is(':checked'))
            checked = true;
                    
    });
    
    //at least one node checked
    if (checked) {
        getSelectedChkBoxes();
        $(".pdfBookletValidator").css("display", "none");   //hide error message        
    }
    else {  //node not checked
        $(".pdfBookletValidator").css("display", "block");  //show error message        
    }

    return checked;

}

//clear session
function clearSession() {
   
    //ajax post
    $.post('http://help.buyitc.si/ajaxpdfbookletfinished.aspx', { manualpdfbookletid: 0, clearsession: 1 },

        function (data) {
            //clear interval
            clearInterval(refreshIntervalId);           
    });    
}

// when DOM loaded load default sub menu
$(document).ready(function () {
    var nodeid = $("#hiddennodeid").val();  //get nodeid for subnavigation
    var manualpdfbookletid = $("#manualpdfbookletid").val();

    //return sub navigation
    postData(nodeid, 0, 0);

    //show or hide link button to the top
    showHideLinkToTop();

    //check if manualpdfbookletid exist
    if ($('#manualpdfbookletid').length > 0 && manualpdfbookletid != "0" && manualpdfbookletid != "") {

        //show popup preparing booklet
        $("#preparingPdfBooklet").css("display", "block");
        $("#finishedPdfBooklet").css("display", "none");
        $("#ajaxLoadGifDiv .ajaxLoadGif").css("display", "block");
        openPopup();

        //check every 3 sec. if booklet generated
        refreshIntervalId = setInterval("checkPdfBookletFinished(" + manualpdfbookletid + ")", 3000);
    }

    try {
        //set focus to username textbox
        if ($("#username").val() == '') {
            document.getElementById("username").focus();
        }
        //set focus to password textbox
        else {
            document.getElementById("password").focus();
        }
    }
    catch (err) {
        //catch when not on default.aspx page
    }
});
