﻿//Copyright 2010 Yontoo technology, Inc.

function msgBox(msg) { alert(msg); }

function PreloadImage(imgSrc) {
    var img = new Image();
    img.src = imgSrc;
}

var currentApplyDiv = null;
var currentLayoutCompleteDiv = null;
var currentLayoutTable = null;
var currentBusyDiv = null;
var pendingLayoutId = null;
var pushedDivs = [];

function pushDiv(div) {
    pushedDivs.push(div);
}

function clearPushedDivs() {
    while (pushedDivs.length > 0) {
        var div = pushedDivs.pop();
        div.style.display = "none";
    }
}

function GlobalShowLayoutDiv(div, table) {
    div.style.position = "absolute";
    clearPushedDivs();

    div.style.display = "inline";
    pushDiv(div);
}

function showLayoutCompleteMessage() {
    if ((typeof (currentLayoutCompleteDiv) === "undefined") || (typeof (currentLayoutTable) === "undefined") || (currentLayoutCompleteDiv === null) || (currentLayoutTable === null)) {
		var successMsg = document.getElementById("successMsg");
		if (successMsg == null) {
			alert('Layout Successfully Removed!');
		} else {
			successMsg.style.display = "block";
			successMsg.style.visibility = "visible";
		}
    }
    else {
        GlobalShowLayoutDiv(currentLayoutCompleteDiv, currentLayoutTable, null);
    }
}

function setCookie(name, value, expMinutes, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());

    if (expMinutes) {
        expMinutes = expMinutes * 1000 * 60;
    }
    var expires_date = new Date(today.getTime() + (expMinutes));

    document.cookie = name + "=" + escape(value) +
                ((expMinutes) ? ";expires=" + expires_date.toGMTString() : "") +
                ((path) ? ";path=" + path : "") +
                ((domain) ? ";domain=" + domain : "") +
                ((secure) ? ";secure" : "");
}

function HandleReadyStateChange() {
    try {
        if (PageRageApplyLayout.xhrApplyLayout.readyState == 4) {
            if (PageRageApplyLayout.xhrApplyLayout.status == 200) {
                switch (PageRageApplyLayout.xhrApplyLayout.responseText) {
                    case "Success":
                        var id = PageRageApplyLayout.getInstallId();
                        if ((id === null) || (id.length === 0)) {
                            msgBox("Please make sure you have Yontoo Layers Installed before selecting a Layout.");
                        }
                        else if ((navigator.appVersion.indexOf('MSIE 6.0') > -1) && (navigator.appVersion.indexOf('MSIE 7.0') == -1) && (navigator.appVersion.indexOf('MSIE 8.0') == -1)) {
                            msgBox("PageRage is not currently supported on IE 6 or earlier. ");
                        }
                        else {
                            showLayoutCompleteMessage();
                        }
                        break;                    
                    case "LayoutNotFound":
                        msgBox("Sorry, that layout could not be found."); //LATER this error could be nicer looking
                        break;
                    case "AuthFail":
                        setCookie("prLayoutId", pendingLayoutId, 60, '/', 'pagerage.com', '');
                        showLayoutCompleteMessage();
                        break;
                    default:
                        //msgBox("Unexpected Error. Please contact PageRage support if this continues. [11]");
                        break;
                }
            }
            else {
                msgBox("Unexpected Error. Please contact PageRage support if this continues. [12][" + xhrSetFBLayoutBrowse.status + "]");  //LATER this error could be nicer looking
            }
            if (currentBusyDiv !== null) {
                currentBusyDiv.style.display = "none";
            }
        }
    }
    catch (ex) {
        msgBox("An error occured while setting the layout."); //LATER this error could be nicer looking
    }
}

function isIE() {
    try {
        if (window.ActiveXObject) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (ex) {
    }
    return false;
}

function isFF() {
    try {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.indexOf("firefox") != -1) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (ex) {
    }
    return false;
}

function isChrome() {
    try {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.indexOf("chrome") != -1) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (ex) {
    }
    return false;
}

function isWin() {
    try {
        if (navigator.appVersion.toLowerCase().indexOf("windows") >= 0) {
            return true;
        }
    }
    catch (ex) {
    }
    return false;
}

function legacyInstall() {
    if (isFF() || isIE() || isChrome()) {
        if (isWin()) {
            document.location.href = "http://download.pagerage.com/PageRageSetup.exe";
            if (isFF()) {
                setTimeout(function() { document.location.href = 'http://www.pagerage.com/InstallYontooPluginFF.aspx'; }, 500);
            }
            else {
                setTimeout(function() { document.location.href = 'http://www.pagerage.com/InstallYontooPluginIE.aspx'; }, 500);
            }
        }
        else {
            document.location.href = "http://download.pagerage.com.com/YontooFFClient.xpi";
        }
    }
    else {
        msgBox("Sorry - Yontoo Layers only works with Firefox or Internet Explorer.");
    }
}

function CheckThirdPartyCookies() {
    try {
        if (window.frames["ctester"] == undefined) {
            var iFrame = document.createElement("iframe");
            iFrame.width = 0;
            iFrame.height = 0;
            iFrame.name = "ctester";
            iFrame.src = "http://www.yontoo.com/CacheTest.aspx";
            iFrame.style.visibility = "hidden";
            document.body.appendChild(iFrame);
        }
    } catch (ex) {
    }
   }

   function checkGuidCookie(name) {
   	var nameEQ, ca, i;
   	nameEQ = name + "="; 													// Declares the <name>= string, used for searching the cookie.
   	ca = document.cookie.split(';'); 										// Breaks the cookie up into its constituent name/value pairs (NVPs)

   	for (i = 0; i < ca.length; i += 1) {									// Loop through each NVP...
   		var c = ca[i]; 														// ... create a temporary variable comprised of this one...
   		while (c.charAt(0) === ' ') {										// ... and while the string we're looking at is empty ...
   			c = c.substring(1, c.length); 									// ... scan along, 1 character at a time until we have something to examine.
   		}
   		if (c.indexOf(nameEQ) === 0) {										// If the name in the NVP we found matches the provided <name>...
   			return c.substring(nameEQ.length, c.length); 					// ... hand its corresponding value back.
   		}
   	} 																		// Otherwise, move on to the next NVP.
   	return null; 															//  If NONE of them match, hand back null.
   }

function BrowseApplyLayout(strLayoutId, layoutCompleteDivId, layoutTableId, busyDiv, retries) {
    try {
        var id = PageRageApplyLayout.getInstallId();        
        setCookie("prLayoutId", strLayoutId, 60, '/', 'pagerage.com', '');
        if ((id === null) || (id.length === 0)) {            
            if (typeof (retries) == "undefined") {
                retries = 4;
            }
            if (retries > 0) {
				setTimeout("try{BrowseApplyLayout('" + strLayoutId + "','" + layoutCompleteDivId + "','" + layoutTableId + "','" + busyDiv + "'," + (retries - 1) + ");}catch(ex){}",200);
				return;
			}

			if (checkGuidCookie("YontooGUID") == "" || checkGuidCookie("YontooGUID") == "ForcedTrue" || checkGuidCookie("YontooGUID") == null || document.cookie.indexOf("YontooGUID") == -1) {
				startInstall();
			}
            return;
        }

        CheckThirdPartyCookies();

        pendingLayoutId = strLayoutId; //can include "remove"

        currentLayoutCompleteDiv = document.getElementById(layoutCompleteDivId);
        currentLayoutTable = document.getElementById(layoutTableId);
        currentBusyDiv = document.getElementById(busyDiv);

        PageRageApplyLayout.ajaxApplyLayout(strLayoutId, true, HandleReadyStateChange,false);

        if ((currentBusyDiv !== null) && (currentLayoutTable !== null)) {
            GlobalShowLayoutDiv(currentBusyDiv, currentLayoutTable, null);
        }
    }
    catch (ex3) {
    }
}

function GetFullTop(node) {
    var offset = 0;
    while (node.offsetParent !== null) {
        offset += node.offsetTop;
        node = node.offsetParent;
    }
    return offset;
}

function GetFullLeft(node) {
    var offset = 0;
    while (node.offsetParent !== null) {
        offset += node.offsetLeft;
        node = node.offsetParent;
    }
    return offset;
}

var bRemove = false;

function MakeRemove() {
    bRemove = true;
}

var y2lRuntimeVersionInstalled = 0;

function GetYontooRuntimeVersionNumber() {
    if (y2lRuntimeVersionInstalled == 0) {
        var apiObject = null;
        try {
            y2lRuntimeVersionInstalled = yontooAPI.getVersionNumber();
        }
        catch (ex) {
            y2lRuntimeVersionInstalled = -1;
        }
    }
    return y2lRuntimeVersionInstalled;
}

var y2lRuntimeVersionStringInstalled = "";
function GetYontooRuntimeVersionString() {
    if (y2lRuntimeVersionStringInstalled.length == 0) {
        try {
            y2lRuntimeVersionStringInstalled = yontooAPI.getVersionString();
        }
        catch (ex) {
            y2lRuntimeVersionStringInstalled = "N/A";
        }
    }
    return y2lRuntimeVersionStringInstalled;
}

function downloadPlugInFile() {
    var ifrm = document.createElement("iframe");
    ifrm.style.width = 1;
    ifrm.style.height = 1;
    ifrm.style.visibility = "hidden";
    ifrm.setAttribute("src", window.downloadUrl);
    document.body.appendChild(ifrm);
    return false;
}

var browserMake = BrowserDetect.browser;
var OSMake = BrowserDetect.OS;

function startInstall() {
    $('#PreInstallContent').css('display', 'block');
    $('#PreInstallHeaderText').css('display', 'block');
    var instOvly = $('#InstallOverlay');
    if (instOvly.css('display') == "none") {
        if ($('#pageRagerObject').length > 0) {
            $('#pageRagerObject').css('display', 'none');
        }
        
        instOvly.css('display', 'block');

        var docLoc = document.location + "";
        docLoc = (docLoc.indexOf("#") != -1) ? docLoc.split("#")[0] : docLoc;
        document.location = docLoc + "#TopSnap";

        if (browserMake == "Firefox" && OSMake == "Mac") {
            window.downloadURL = "http://download.pagerage.com/YontooFFClient.xpi";
            findObj("FFInstallOLScreenshots").style.backgroundPosition = "0px -986px";
            var instBtnlink = findObj("InstallForceDownloadInstallLink");
            instBtnlink.href = "http://download.pagerage.com/YontooFFClient.xpi";
            setTimeout(function () {
                docLoc = (docLoc.indexOf("#") != -1) ? docLoc.split("#")[0] : docLoc;
                docLoc = (docLoc.indexOf("?") != -1) ? docLoc.split("?")[0] : docLoc;
                document.location = docLoc + "#Go2Success";
            }, 1000);
        }
        
        downloadPlugInFile();
        // Set default layout if one hasn't been selected
        checkLayoutCookie();

    } else {
        if ($('#pageRagerObject').length > 0) {
            $('#pageRagerObject').css('display', 'block');
        }

        instOvly.css('display', 'none');
        
        var docLoc = document.location + "";
        docLoc = docLoc.replace("#Go2Success", "");
        document.location = docLoc;
    }
    return false;
}

function loadSuccess() {
    findObj("PreInstallContent").style.display = "none";
    findObj("PreInstallHeaderText").style.display = "none";
    findObj("InstallOverlay").style.display = "block";
}

function showModal(ShowCode) {
    findObj("InstallContent").style.display = "none";
    findObj("InstallOverlay").style.display = "block";
    findObj("AdditionalPreviews").style.display = "block";
    findObj("AdditionalPreviews").innerHTML = ShowCode;
}

function hideModal() {
    findObj("InstallContent").style.display = "block";
    findObj("InstallOverlay").style.display = "none";
    findObj("AdditionalPreviews").style.display = "none";
    findObj("AdditionalPreviews").innerHTML = "";
}


var docLoc = document.location + "";
if (docLoc.indexOf("Default2.aspx#Success") != -1) {
    if (typeof (window.onload) != "function") {
        window.onload = loadSuccess;
    } else {
        var currOnLoad = window.onload;
        window.onload = function () {
            currOnLoad();
            loadSuccess();
        }
    }
}

// Sub-Nav Pop-Up Menus
var activelyHovering1 = false;
var activelyHovering2 = false;

function subnavFlyoutMenus(LinkObj, MenuID, ShowState) {
	var relevantHoverCheck = eval("activelyHovering" + MenuID);
	var targetMenu = findObj("SubNavPopup" + MenuID);
	if (ShowState) {
		targetMenu.style.display = "block";
		LinkObj.className = "SubNavPopupLinkOn";
	} else {
		if (relevantHoverCheck) return false;
		targetMenu.style.display = "none";
		LinkObj.className = "SubNavPopupLinkOff";
	}
}

function hideSubnavFlyouts(LinkObj, MenuID) {
	setTimeout(function () { subnavFlyoutMenus(LinkObj, MenuID, false) }, 100);
}

