/// <reference name="MicrosoftAjax.js"/>
/// <reference name="MicrosoftAjax.Debug.js"/>

var globalStartupContentFieldId = "GlobalStartupWaitContent";
var printInformationLayerLinkId = "PrintInformationLayerLink";

function CreateBookmarkLink(title, url) 
{ 	
    url = unescape(url);
    title = unescape(title);
    if (window.sidebar) {
        // Mozilla Firefox Bookmark		
        window.sidebar.addPanel(title, url, "");
    }
    else if (window.external) {
        // IE Favorite		
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) {
        // Opera Hotlist		
        return true;
    }
}

function SetLeftAlignment(controlToMoveID, controlAlignID) {
    var alignElem = $get(controlAlignID);
    var moveElem = $get(controlToMoveID);
    if (alignElem != null && alignElem != "undefined" &&
        moveElem != null && moveElem != "undefined") {
        var clientPosX = alignElem.offsetLeft;
        var controlPosX = moveElem.offsetLeft;
        var posX = 0;
        posX = clientPosX - controlPosX;

        var controlMarginLeft = new String();
        controlMarginLeft = moveElem.style.marginLeft;

        var controlMarginLeftNew = 0;
        if (controlMarginLeft != null && controlMarginLeft.length > 0) {
            if (controlMarginLeft.indexOf("px", 0) != -1) {
                controlMarginLeftNew = controlMarginLeft.substring(0, controlMarginLeft.length - 2);
            }
            else {
                controlMarginLeftNew = controlMarginLeft;
            }
        }

        controlMarginLeftNew = (parseInt(controlMarginLeftNew) + parseInt(posX));
        
        if (controlMarginLeftNew > 0) {
            moveElem.style.marginLeft = controlMarginLeftNew.toString() + "px";
        }
    }

    return true;
}

function ShowControls(controlArray) {
    if (controlArray != null && controlArray.length > 0) {
        var elem;
        for (i = 0; i < controlArray.length; i++) {
            elem = $get(controlArray[i]);

            if (elem != null && elem != "undefined") {
                elem.style.display = "block";
            }
        }
    }
}

function HideControls(controlArray) {
    if (controlArray != null && controlArray.length > 0) {
        var elem;
        for (i = 0; i < controlArray.length; i++) {
            elem = $get(controlArray[i]);

            if (elem != null && elem != "undefined") {
                elem.style.display = "none";
            }
        }
    }
}

function CheckLength(control, maxLength) {
    if (control.value.length >= maxLength) {
        if (event == null) {
            return false;
        }
        else {
            event.returnValue = false;
        }
    }
}

function SwitchTab(tabID, index) {
    var tab = igtab_getTabById(tabID);
    if (tab == null) {
        return;
    }

    tab.setSelectedIndex(index);
}

function fireEvent (eventType, elementID) 
{
    var o = document.getElementById(elementID);
    var evt;
    if (document.createEvent) 
    { 
        evt = document.createEvent("Events"); 
        evt.initEvent(eventType, true, true);
         o.dispatchEvent(evt); 
    } 
    else if (document.createEventObject) 
    { 
        evt = document.createEventObject(); 
        o.fireEvent('on' + eventType, evt); 
    } 
}

function clickButton(e, buttonid)
{
    var evt = e ? e : window.event;   
    if (evt.keyCode == 13)
    {  
        fireEvent("click", buttonid);
        return false; 
    }    
}

function ActivateIGTab(webTab, tabIndex)
{
    if (webTab == null)
    {
        return;
    }
    if (tabIndex == null)
    {
        tabIndex = GetQueryStringParameterValue("tabindex")
        if (tabIndex == null || tabIndex == "")
        {
          return;
        }
    }
    webTab.setSelectedIndex(tabIndex);
}

function GetQueryStringParameterValue(key)
{
  var value = new String();
  var query = window.location.search;
  key = key.toLowerCase();
  query = query.replace(/\?/g, "");
  if (query.toLowerCase().indexOf(key + "=") == -1)
  {
      return null;
  }
  queryFields = query.split("&");
  for (i = 0; i < queryFields.length; i++)
  {
      if (queryFields[i].toLowerCase().indexOf(key + "=") != -1)
      {
          value = queryFields[i].substring(queryFields[i].indexOf("=") + 1);
      }
  }
  return value;
}

function CourseDetailTab_InitializeTabs(oWebTab)
{
    ActivateIGTab(oWebTab);
}

function SetVisibilityForDOMElement(elementid, value)
{
    var domElement = window.document.getElementById(elementid);
    if (domElement != null && domElement != "undefined")
    {
        domElement.style.visibility = value;
    }
}

function CopyNodes(sourceId, targetId)
{
  var sourceElement = $get(sourceId);
  var targetElement = $get(targetId);
  if (sourceElement != null && sourceElement != "undefined" &&
      targetElement != null && targetElement != "undefined")
  {
    var sourceChildElements = sourceElement.children;
    while (sourceChildElements.length > 0)
    {
      targetElement.appendChild(sourceChildElements[0]);
    }
    sourceElement.parentNode.removeChild(sourceElement);
  }
}

function GetSelectedText(dropDownElement)
{
    var selectedIndex = dropDownElement.selectedIndex;
    var optionCollection = dropDownElement.options;
    var returnText = new String();
    if (selectedIndex > 0)
    {
        var option = optionCollection[selectedIndex];
        returnText = option.text;
    }
    
    return returnText;
}

function GetSelectedValue(dropDownElement)
    {
        var selectedIndex = dropDownElement.selectedIndex;
        var optionCollection = dropDownElement.options;
        var returnText = new String();
                
//        if (selectedIndex > 0)
//        {
            var option = optionCollection[selectedIndex];
            returnText = option.value;
//        }
        
        return returnText;
    }

function SetTextForInputBox(elementId, value)
{
    var domElement = window.document.getElementById(elementId);
    if (domElement != null && domElement != "undefined")
    {
        domElement.value = value;
    }
}

// Public - Tree node click event.
function ADTree1_NodeClick(treeId, nodeId, buttonId)
{
    if (buttonId == 2)
    {
        return false;
    }
    var oNode = igtree_getNodeById(nodeId);
    if (oNode != null)
    {
        var dataKey = adTree_getDataKey(oNode, "|");
        var sourceDataKey = adTree_getSourceDataKey(oNode, "|");
        var nodeText = escape(oNode.getText());
        window.setTimeout("CallNodeClick('" + dataKey + "', '" + nodeText + "', '" + sourceDataKey + "', '" + treeId + "');", 10);
    }
    
    return false;
}

//Private
function CallNodeClick(dataKey, nodeText, sourceDataKey, treeId)
{
    var oTree = igtree_getTreeById(treeId);
    
    CallCollectGarbage();
    nodeText = unescape(nodeText);
    try
    {
        window.location.href = window.location.pathname + "?dataKey=" + dataKey;
        //HandleLoadFromFavorites();
    }
    catch(e)
    {}
}

// Private - Collecting Garbage if possible
function CallCollectGarbage()
{
    if (typeof(CollectGarbage) != "undefined")
    {
        CollectGarbage();
    }
}

function SetSearchSource(sourceUrl, iframeId, inputId)
{
    var searchIFrame = $get(iframeId);
    var searchInput = $get(inputId);
    if (searchIFrame != null && searchIFrame != "undefined" &&
        searchInput != null && searchInput != "undefined")
    {
        var searchUrl = sourceUrl + "?search=" + searchInput.value;
        
        document.location.href= searchUrl;       
        //searchIFrame.src = searchUrl;
    }
}

function CloseVisibleToolkitPopup()
{
  if (AjaxControlToolkit.PopupControlBehavior != null && AjaxControlToolkit.PopupControlBehavior != "undefined" &&
      AjaxControlToolkit.PopupControlBehavior.__VisiblePopup != null && AjaxControlToolkit.PopupControlBehavior.__VisiblePopup != "undefined")
  {
    AjaxControlToolkit.PopupControlBehavior.__VisiblePopup.hidePopup();
  }
}

function InitRequestManager()
{
  var sitrainRequestManager = Sys.WebForms.PageRequestManager.getInstance();
  if (sitrainRequestManager != null) {
    sitrainRequestManager.add_beginRequest(BeginRequestHandler);
    sitrainRequestManager.add_endRequest(EndRequestHandler);
  }

  var currentHash = window.location.hash;
  if ((currentHash.length > 0) && (currentHash.charAt(0) == "#")) {
      currentHash = currentHash.substring(1);
  }

  var hashFields = currentHash.split("&");
  var showLoginLayer = false;
  var elementID = new String();
  
  for (i = 0; i < hashFields.length; i++) {
      if (hashFields[i].toLowerCase().indexOf("showloginlayer") != -1) {
          showLoginLayer = true;
          var paramKeyValue = hashFields[i].split("=");
          if (paramKeyValue.length === 2) {
              elementID = paramKeyValue[1];
              fireEvent("click", elementID);
          }
      }
  }
}

function BeginRequestHandler(sender, args)
{
  var waitControl = $get("GlobalWaitControl");
  if (waitControl != null && waitControl != "undefined")
  {
    waitControl.style.display = "block";
  }
}

function EndRequestHandler(sender, args)
{
  var waitControl = $get("GlobalWaitControl");
  if (waitControl != null && waitControl != "undefined")
  {
    waitControl.style.display = "none";
  }
}


function SetDefaultWaitContent(resultFieldId)
{
  var result = false;
  var resultElement = $get(resultFieldId);
  if (resultElement != null && resultElement != "undefined")
  {
    var startupElement = $get(globalStartupContentFieldId);
    if (startupElement != null && startupElement != "undefined")
    {
      resultElement.innerHTML = startupElement.innerHTML;
      result = true;
    }
    else
    {
      resultElement.innerHTML = "";
    }
  }
  return result;
}

function GetActivityInfo(resultFieldId, activityId)
{
  SetDefaultWaitContent(resultFieldId);
  SiTrain.WebServices.GlobalContent.GetActivityInfo(activityId, SucceedCallback, FailedCallback, resultFieldId);
}

function GetCourseInfo(resultFieldId, courseId)
{
  SetDefaultWaitContent(resultFieldId);
  SiTrain.WebServices.GlobalContent.GetCourseInfo(courseId, SucceedCallback, FailedCallback, resultFieldId);
}

function GetLocationInfo(resultFieldId, locationSign)
{
  SetDefaultWaitContent(resultFieldId);
  SiTrain.WebServices.GlobalContent.GetLocationInfo(locationSign, SucceedCallback, FailedCallback, resultFieldId);
}

function FailedCallback(error)
{}

function SucceedCallback(result, userContext, methodName)
{
  var resultElement = $get(userContext);
  if (resultElement != null && resultElement != "undefined")
  {
    resultElement.innerHTML = result;
  }
}

function customResize()
{
    var content = document.getElementById('content');
    var feat = document.getElementById('featureColumn');

        var x,y;
    if (self.innerHeight) // all except Explorer
    {
        x = self.innerWidth;
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
    {
        x = document.documentElement.clientWidth;
        y = document.documentElement.clientHeight;
    }
    else if (document.body) // other Explorers
    {
        x = document.body.clientWidth;
        y = document.body.clientHeight;
    }

    var width = document.body.clientWidth;
    var height = y; // document.body.clientHeight;

    content.style.width = width - 344;
    content.style.height = y - 167;

    featureColumn.style.width = 340;
    featureColumn.style.height = y - 167;
 }
 
 // Public - Loads a bookmarked page and sets the url-hash to the query-string.
function HandleLoadFromFavorites()
{
    var currentUrl = new String();
    currentUrl = window.location.href;
    var hash = window.location.hash;
    if ((hash.length > 0) && (hash.charAt(0) == "#"))
        hash = hash.substring(1);
    var hashFields = hash.split("&");
    var query = new String();
    var url = new String();
    
    if (currentUrl.indexOf("?") != -1)
    {
        query = currentUrl.substring(currentUrl.indexOf("?")).indexOf("#") != -1 ?
            currentUrl.substring(currentUrl.indexOf("?")+1, currentUrl.indexOf("#")) :
            currentUrl.substring(currentUrl.indexOf("?")+1);
        query = GetCleanedQuerystring(query, "nodeId", false);
        query = GetCleanedQuerystring(query, "dataKey", false);
        query = GetCleanedQuerystring(query, "config", false);
        query = "?" + query;
        url = currentUrl.substring(0, currentUrl.indexOf("?"));
    }
    else
    {
        if (hash.length > 0)
            url = currentUrl.substring(0, currentUrl.indexOf("#")) + "?";
        else
            url = currentUrl;
    }
    
    var nodeId = new String();
    var key = new String();
    var config = new String();
    for (i = 0; i < hashFields.length; i++)
    {
        if (hashFields[i].toLowerCase().indexOf("nodeid") != -1)
            nodeId = hashFields[i];
        if (hashFields[i].toLowerCase().indexOf("datakey") != -1)
            key = hashFields[i];
        if (hashFields[i].toLowerCase().indexOf("config") != -1)
            config = hashFields[i];
    }
    if (nodeId.length > 0 && (key.length > 0 | config.length > 0))
        nodeId += "&";
    if (key.length > 0 && config.length > 0)
        key += "&";
    if ((nodeId.length > 0) || (key.length > 0) || (config.length > 0))
        window.location.href = url + query + nodeId + key + config;
}

function Cover(bottom, top) {
    //var location = Sys.UI.DomElement.getLocation(bottom);
   //top.style.position = 'absolute';
    //top.style.top = (location.y - 5) + 'px';
    //top.style.right = "0px";
}

function ShowLoginPanel(clickedElementID, panelID, containerID, contentFrameID, loginUrl, emptyUrl) {
    var clickedElement = $get(clickedElementID);
    var panel = $get(panelID);
    var container = $get(containerID);
    var contentFrame = $get(contentFrameID);
    var loginUrlUnescaped = unescape(loginUrl);

    if (clickedElement === null || panel === null || container === null || contentFrame === null) {
        return;
    }
    
    if (panel.style.display === "block") {
        HideLoginPanel(panelID, containerID, contentFrameID, emptyUrl);
    }
    else {
        if (!CheckProtocol()) {
            ChangeProtocol("ShowLoginLayer", clickedElementID);
            return;
        }
        Cover(clickedElement, panel);
        contentFrame.src = loginUrlUnescaped;
        container.className = "active";
        panel.style.display = "block";
    }
}

function HideLoginPanel(panelID, containerID, contentFrameID, emptyUrl) {
    var panel = $get(panelID);
    
    var container;
    if (containerID.constructor === Array) {
        for (i = 0; i < containerID.length; i++) {
            container = $get(containerID[i]);
            if (container !== null) {
                break;
            }
        }
    }
    else {
        container = $get(containerID);
    }
    
    var contentFrame = $get(contentFrameID);
    var emptyUrlUnescaped = unescape(emptyUrl);

    if (panel === null || container === null || contentFrame === null) {
        return;
    }
    
    panel.style.display = "none";
    container.className = "";
    contentFrame.src = emptyUrlUnescaped;
}

function CheckProtocol() {
    var currentProtocol = window.location.protocol;

    return (currentProtocol == "https:");
}

function ChangeProtocol(paramName, paramValue) {
    var currentLocation = window.location.href;

    currentLocation = currentLocation.replace(window.document.location.protocol, "https:");
    currentLocation = AddHashParamToLocation(currentLocation, paramName, paramValue);

    window.location.href = currentLocation;
}

function AddHashParamToLocation(oldLocation, hashParamName, hashParamValue) {
    var hash = new String();
    var newLocation = oldLocation;

    locationHashIndex = oldLocation.indexOf("#");
    if (locationHashIndex >= 0) {
        hash = oldLocation.substring(locationHashIndex + 1);
        newLocation = oldLocation.substring(0, locationHashIndex);
    }

    if (hash.length > 0) {
        hash = GetCleanedQuerystring(hash, hashParamName, true);
    }

    if (hash.length > 0) {
        hash += "&";
    }

    hash = "#" + hash + hashParamName + "=" + hashParamValue;

    newLocation += hash;

    return newLocation;
}

// Public - Gets a new query-string representation from the passed query-string, cleaned from the passed parameter.
function GetCleanedQuerystring(queryString, parameterName, caseSensitive)
{
    var queryComponents = new String();
    queryComponents = queryString.split("&");
    newQuery = new String();
    var queryComponent = new String();
    for (i = 0; i < queryComponents.length; i++)
    {
        if (!caseSensitive)
        {
            queryComponent = queryComponents[i].toLowerCase();
            parameterName = parameterName.toLowerCase();
        }
        else
        {
            queryComponent = queryComponents[i];
        }
            
        if ((queryComponent.length > 0) && (queryComponent.indexOf(parameterName) == -1))
        {
            newQuery += queryComponents[i];
            if (i < queryComponents.length - 1) {
                newQuery += "&";
            }
        }
    }
    if ((newQuery.lastIndexOf("&") == (newQuery.length-1)) && newQuery.length > 0)
    {
        //newQuery = newQuery.substring(0, newQuery.length-2);
    }
    return newQuery;
}

function openPrintDialog(url)
	{
	    window.open(url, "", "scrollbars=yes,width=720,height=800,menubar=yes,locationbar=no,status=no,resizable=yes,dependent=yes"); 
	}
	
function printCurrentContactWorldwide()
{
    if(currenctSelectedContactWorldwide)
    {
        var url = "./print/printcontactworldwide.aspx?country=" + currenctSelectedContactWorldwide;
        openPrintDialog(url);	        
    }
}
	
function printWhyTraining( )
{
    openPrintDialog("./print/printwhytraining.aspx");
}

function printContactLayer( )
{
    openPrintDialog("./print/printcontactlayer.aspx");
}

// Dummy method for sharepoint-scrapy implementation.
function imageloadcomplete(dummy)
{ }

function PrintDynamicContent(query)
{
    openPrintDialog("./print/printdynamiccontent.aspx?" + query);
}
/* END: content layer     */

if( typeof(Sys) != "undefined" && typeof(Sys.Application) != "undefined" )
{
    Sys.Application.notifyScriptLoaded();
}
