﻿$(document).ready(function() {
    GetPage(GetCurrentPage());
    $(window).bind('resize', function() {
        //PositionHeaderMenu();
    });
});

var InteractionContext = {
    Page: 1,
    Record: 2
};


var isModalWindowShowed = false;
var isLanguageChanged = false;
var isFirstTimeLoad = true;
var context = null;
var lastViewedRecord = null;
var currentPageObj = null;
var prevLoadedPage = null;
var lastViewedWindow = null;
// Use to keep track of modal language change
var isWindowLanguageChange = false;
//Use to keep track if the current request is completely done or not.
var loadSuccessful = true;

function GetPage(pagePath) {
    // Fetch Page content
    if(pagePath == prevLoadedPage)
    {
        if((pagePath.indexOf('/Profile') > 0
						    || pagePath.indexOf('/Contacts') > 0))
		     {
		        return;
		     }
        PopulateContents(currentPageObj, false);
        return;
    }
    

    if (pagePath != prevLoadedPage && loadSuccessful) {
        // As request is processing loadSuccessful set to false;
        loadSuccessful = false;
        // Link cursor will be shown busy(wait)
        ToggleAllinkCursorStates();
        prevLoadedPage = pagePath;
        isDifferentLanguageSelected = false;
        
        HITCMSProxy.FetchPage(pagePath, function(page) {
            if (pagePath.indexOf('/Profile') > 0
						    || pagePath.indexOf('/Contacts') > 0 //|| pagePath.indexOf('/Vacancies') > 0
						    ) {
                ShowWindow(page, pagePath);
                lastViewedWindow = page;
            } else {
                lastViewedRecord = null;
                // set current page path
                SetCurrentPage(pagePath);
                PopulateContents(page, true);
                currentPageObj = page;
            }
            //After completion of the page load loadSuccessful set to true;
             loadSuccessful = true;
             ToggleAllinkCursorStates()
            if (isFirstTimeLoad && window.location.toString().indexOf(".nl") != -1) 
            {
                if (typeof $.cookie('lan') == 'undefined' || $.cookie('lan') == null|| $.cookie('lan') == '')
                    SetLanguage("nl");
            }
            isFirstTimeLoad = false;
            SetTopMenuSelected();
        });
    }

    /*
    * if ($(".topmenuselected").length > 0) $(".topmenuselected")[0].className =
    * "topmenu"; var pageElement = $("#link" + pagePath.split('/')[1]); if
    * (typeof pageElement != 'undefined' || pageElement != null) {
    * pageElement.attr("class", "topmenuselected"); }
    */

}

/* This "PopulateContentsCallCounter" value is used only for stop recursion 
of the following function when it will be called again for submenu collapse.
After collapse, first PopulateContents() will be called and its value will be increased by one,
2nd time it will be called but the condition fail as PopulateContentsCallCounter value reach more
than 1. Its value reset when I click in any submenu item. ie. It ready for collapse again.
*/
var PopulateContentsCallCounter = 0;

function PopulateContents(page, changeHeaderBG) {
    if (changeHeaderBG) {
        SetHeaderBackground(page.settings.backgroundImageUrl);
    }
    
    var pageBodyTitle = "";
    var pageBodyText = "";
    if (GetCurrentLanguage() == 'en') {
        pageBodyText = unescape(page.text.html_en);
        pageBodyTitle = unescape(page.text.title_en);
        $("#linkEnglish").attr("class", "selectedLanguage");
    } else if (GetCurrentLanguage() == 'nl') {
        pageBodyText = unescape(page.text.html_nl);
        pageBodyTitle = unescape(page.text.title_nl);
        $("#linkDutch").attr("class", "selectedLanguage");
    }
    ////////HTML form for Vancency///////
    /// alert(GetCurrentPage());

    if (GetCurrentPage() == 'Home/Vacancies') {
        var formstr = "";
        //        formstr += '<form method="POST" id="frm1" action=\'UploadHandler.ashx\' enctype=\'multipart/form-data\'>';
        //        formstr += '<input type=\'file\' name=\'file1\' value=\'click me\' />';
        //        formstr += '<input type=\'button\' value=\'click me\' onclick="frm1.submit();"></input>';
        //        formstr += '</form>';

        formstr += '<iframe src ="Vacancies.aspx" width="90%" border="0" frameborder="0" height="150"></iframe>';

        //alert(formstr)
        pageBodyText = pageBodyText + formstr;

    }
    //alert(pageBodyText);
    ////////////////////////////////

    var isMenuType = false;
    if (page.Collections != null) {
        $.each(page.Collections, function(coll) {
            if (page.Collections[coll].type == 'menu') {
                isMenuType = true;
            }
        });
    }
    if (isMenuType) {
        $($('#pageLeftPanel')).Menu({
            Collections: page.Collections,
            className: "hitMenu",
            subMenuClassName: 'hitSubMenu',
            animate: false,
            footerClassName: 'hitMenuFooter'
        }).bind("submenuClick", function(event, record) {
            ViewRecord(record);
            PopulateContentsCallCounter = 0;
        }).bind("AllItemsCollapsed", function() {
                /* Here PopulateContentsCallCounter is checked, 
                   If it come here for 2nd time it will return */
                if (currentPageObj != null && PopulateContentsCallCounter <= 1) {
                PopulateContentsCallCounter++;
                PopulateContents(currentPageObj, false);
                lastViewedRecord = null;
            }
            else
            {
                return;
            }
        });
    } else {
        RenderLoginControl();
    }
    var panelBackgroundImage = "imagedata/nopic.gif";
    if (page.settings.panelBackImage != null) {
        panelBackgroundImage = HITConstants.HITCMSSiteUrl + "ImageHandler.ashx?url=" + page.settings.panelBackImage + "&WebSiteId=" + HITConstants.WebSiteId + "&width=200";
    }
    $('#pageMiddlePanel').Panel({
        titleClass: 'panelheadertext',
        title: pageBodyTitle,
        textPanelClass: 'paneltext',
        panelText: pageBodyText,
        panelImageUrl: panelBackgroundImage,
        panelImageWidth: 200,
        panelImageHeight: 200,
        height:350,
        width: 625,
        animate: isLanguageChanged,
        panelTextClass: "paneltext"
    });
    document.getElementById('pageMiddlePanel').scrollTop = 0;
    context = InteractionContext.Page;
    isLanguageChanged = false;
}

function ViewRecord(record) {
 /*
    The following 2 line will stop to populate content for the same submenu click.
  
 */
 
//    if(record == lastViewedRecord)
        //{
//        return;
        //}

    var pageBodyTitle = "";
    var pageBodyText = "";
    var panelImageUrl = "imagedata/nopic.gif";
    if (record.advanced != null && record.advanced.panelimage != null) {
        panelImageUrl = HITConstants.HITCMSSiteUrl + "ImageHandler.ashx?url=" + record.advanced.panelimage + "&WebSiteId=" + HITConstants.WebSiteId + "&width=200";
    }
    
    if (GetCurrentLanguage() == 'en') {
        pageBodyText = unescape(record.collectionText.panelText_en);
        pageBodyTitle = unescape(record.collectionText.panelHeader_en);
    } else if (GetCurrentLanguage() == 'nl') {
        pageBodyText = unescape(record.collectionText.panelText_nl);
        pageBodyTitle = unescape(record.collectionText.panelHeader_nl);
    }
    $('#pageMiddlePanel').Panel({
        titleClass: 'panelheadertext',
        title: pageBodyTitle,
        textPanelClass: 'paneltext',
        panelText: pageBodyText,
        panelImageUrl: panelImageUrl,
        panelImageWidth: 200,
        panelImageHeight: 200,
        width: 625,
        height:350,
        animate: false,
        panelTextClass: "paneltext"
    });
    document.getElementById('pageMiddlePanel').scrollTop = 0;
    context = InteractionContext.Record;
    lastViewedRecord = record;
}

function MenuMouseOver(menuItem)
{
    if(loadSuccessful)
    {
        document.getElementById(menuItem).style.backgroundColor = "#0189d8";
    }
}



function ToggleAllinkCursorStates()
{
 if(!loadSuccessful)
   {
     $('body').css('cursor', 'wait'); 
     $('.headerPageMenu').css('cursor','wait');
     $('a').css('cursor', 'wait');
     $('.hitMenuItem').css('cursor','wait');
     $('.hitSubMenu').css('cursor','wait');
  }
 else
  {
    $('body').css('cursor', 'auto'); 
    $('.headerPageMenu').css('cursor','pointer');
    $('a').css('cursor', 'pointer');
    $("#blankLink").css('cursor','auto');
    $('.hitMenuItem').css('cursor','pointer');
    $('.hitSubMenu').css('cursor','pointer');
  }
}

function SetTopMenuSelected() {
    var selectedTopMenu = null;
    var notSelectedMenu = null;
    if (GetCurrentPage() == 'Home/Vacancies') {
        selectedTopMenu = $("#linkVacancies");
        notSelectedMenu = $("#linkHome");
    }
    else //if(GetCurrentPage() == 'Home/Home')
    {
        selectedTopMenu = $("#linkHome");
        notSelectedMenu = $("#linkVacancies");
    }

    if (selectedTopMenu != null && notSelectedMenu != null) {
        notSelectedMenu.attr("class", "topmenu");
        selectedTopMenu.attr("class", "topmenuselected");
    }
}

function SetLanguage(language) {
    $.cookie('lan', language);
    var languageElement = null;
    if (language == 'en') {
        languageElement = $("#linkEnglish");
        nonLanguageElement = $("#linkDutch");
    } else {
        languageElement = $("#linkDutch");
        nonLanguageElement = $("#linkEnglish");
    }
    isWindowLanguageChange = false;
    if (languageElement.attr("class") != "selectedLanguage") {
        if(lastViewedRecord != null )
        {
            ViewRecord(lastViewedRecord);
        }
        else
        {
            PopulateContents(currentPageObj, false);
        }
        
        // This portion will change the modal's language
        if(lastViewedWindow!= null)
        {
            isWindowLanguageChange = true;
            ShowWindow(lastViewedWindow, prevLoadedPage);
        }

        isLanguageChanged = true;

        languageElement.attr("class", "selectedLanguage");
        nonLanguageElement.attr("class","topmenu");
    }


}

function SetCurrentPage(path) {
    $.cookie('currentPage', path);
}

function GetCurrentPage() {
    if (typeof $.cookie('currentPage') == 'undefined'
			|| $.cookie('currentPage') == null || $.cookie('currentPage') == '')
        return 'Home/Home';
    return $.cookie("currentPage");
}

function GetCurrentLanguage() {
    if (typeof $.cookie('lan') == 'undefined' || $.cookie('lan') == null
			|| $.cookie('lan') == '')
        return 'en';
    return $.cookie('lan');
}

function SetHeaderBackground(imageUrl) {
    if (!isLanguageChanged) {
        var pageHeader = document.getElementById("pageHeader");
        if (pageHeader.style.backgroundImage.toLowerCase() != "url("
				+ imageUrl.toLowerCase() + ")") {
            var backImageUrl = "url('" + HITConstants.HITCMSSiteUrl + "ImageHandler.ashx?url=" + imageUrl + "&WebSiteId=" + HITConstants.WebSiteId + "')";
            pageHeader.style.backgroundImage = backImageUrl;
            //pageHeader.style.display = "none";
            //$("#pageHeader").fadeIn('slow');
        }
        //PositionHeaderMenu();
    }
}

function PositionHeaderMenu() {
    var opacAOffset = $("#opacMenuArea").offset();
    $("#divPageMenu").css({
        "left": opacAOffset.left,
        "top": opacAOffset.top
    });
}

function RenderLoginControl() {
    var loginHTML = "<div style='width:196px;border:1px solid gray;'><div class='userpaneltext' style='padding:10px;'>"
			+ "<span>Hawar Information Technology Data Service Provider instantly provides access to your geographical data.</span></div>"
			+ "<table style='background-color:#cccccc;padding-left:10px;font-size:0.9em;width:196px'>"
			+ "<tr class='userpaneltext'><td><span>Project</span></td><td><input type='text' class='userinputbox'/></td></tr>"
			+ "<tr class='userpaneltext'><td><span>User Name</span></td><td><input type='text' class='userinputbox' /></td></tr>"
			+ "<tr class='userpaneltext'><td><span>Password</span></td><td><input type='password' class='userinputbox' /></td></tr>"
			+ "<tr><td>&nbsp;</td><td align='left'><img src='images/submit.gif' style='cursor: pointer; margin-left: 1px;' onclick='showInvalidAccount();'/></td></tr>"
			+ "</table><div class='userpanelfooterdiv'><span class='homebottommenufooter'></span></div></div>";

    $("#pageLeftPanel").html(loginHTML);
}

function ShowWindow(page, pagePath) {
    
    var pageBodyTitle = "";
    var pageBodyText = "";
    if (GetCurrentLanguage() == 'en') {
        pageBodyText = unescape(page.text.html_en);
        pageBodyTitle = unescape(page.text.title_en);
    } else if (GetCurrentLanguage() == 'nl') {
        pageBodyText = unescape(page.text.html_nl);
        pageBodyTitle = unescape(page.text.title_nl);
    }
    var panelBackgroundImage = "imagedata/nopic.gif";
    if (page.settings.panelBackImage != null) {
        panelBackgroundImage = HITConstants.HITCMSSiteUrl + "ImageHandler.ashx?url=" + page.settings.panelBackImage + "&WebSiteId=" + HITConstants.WebSiteId;
    }

    // If request come to change the language of modal text
    if(isWindowLanguageChange)
    {
        isWindowLanguageChange = false;
      
        $("#modalWindowDiv").Panel({
        title: '',
        panelText: pageBodyText,
        panelImageUrl: panelBackgroundImage,
        panelTextClass: "paneltext2"
        });
//        context = InteractionContext.Page;
//        isLanguageChanged = false;
//        isModalWindowShowed = true;
        return;
    }
    
    //first close any existing window
    
    if(isModalWindowShowed)
    {
        closeExistingDialog(pagePath);
    }
    
    if(document.getElementById("modalWindowDiv")!=null)
    {
         if ($('.ui-dialog').length > 0) 
         {
               try
               {
                document.body.removeChild($('.ui-dialog')[0]);
               }
               catch(Error )
               {
                //
               }
         }
    }
    
    var elm = document.createElement("div");
        elm.setAttribute("id","modalWindowDiv");
        
    var cldElm = document.createElement("div");

    $(elm).Panel({
        title: '',
        panelText: pageBodyText,
        panelImageUrl: panelBackgroundImage,
        panelTextClass: "paneltext2"
    }).dialog({
        title: page.name,
        width: 600,
        resizable: false,
        drag: function() {
            $(this).css({ 'opacity': 0.2, 'filter': 'alpha(opacity=20)' });
        },
        dragStop: function() {
            $(this).css({ 'opacity': 1.0, 'filter': 'alpha(opacity=100)' });
        },
        close: function(){
            isWindowLanguageChange = false;
            isModalWindowShowed = false;
            prevLoadedPage = GetCurrentPage();
            lastViewedWindow = null;
            closeExistingDialog(pagePath);
        },
        hide: 'scale',
        show: 'scale'
    });
    context = InteractionContext.Page;
    isLanguageChanged = false;
    isModalWindowShowed = true;
    //$(elm).dialog();
    //$(elm).dialog({});
}

function closeExistingDialog(pagePath) {

    if(pagePath != prevLoadedPage){
        prevLoadedPage = GetCurrentPage();
    }
    
    isModalWindowShowed = false;
    isWindowLanguageChange = false;
    
    
    while($('.ui-dialog').length > 0)
     {
            try
            {
              document.body.removeChild($('.ui-dialog')[0]);
            }
            catch(Error )
            {
                break;
            }
    }
    while ($('.ui-widget-shadow').length > 0) 
    {
        try
        {
            document.body.removeChild($('.ui-widget-shadow')[0]);
        }
        catch(Error )
        {
                break;
        }
    }
}

function showInvalidAccount() {
    var elm = document.createElement("div");
    elm.innerHTML = "<p style='margin-top:15px;'><center><strong style='color:red'>Invalid account!</strong></center></p>";
    $(elm).dialog({
        title: "Online Services",
        resizable: false,
        drag: function() {
            $(this).css({ 'opacity': 0.2, 'filter': 'alpha(opacity=20)' });

        },
        dragStop: function() {
            $(this).css({ 'opacity': 1.0, 'filter': 'alpha(opacity=100)' });
        },
        hide: 'scale',
        show: 'scale'
    });
}