﻿//----------------------------------------- CONSTANTS -----------------------------------------------/
var GadgetXOffset = 15;  //default horizontal distance from the top/left of the keyword in which the tooltip will appear
var GadgetYOffset = 20;  //default vertical distance from the top/left of the keyword in which the tooltip will appear
var DelayInterval = 500; //delay time when show or close gadget, microsenconds
/* CREATIVE WIDTH -------------- Initial display width (in pixels) of the gadget */
var GadgetWidth = new Array();
GadgetWidth[0] = 275;   //Full Gadget
GadgetWidth[1] = 200;   //Video of Quickbar
GadgetWidth[2] = 200;   //Music of Quickbar
GadgetWidth[3] = 200;   //Photo of Quickbar
GadgetWidth[4] = 200;   //Profile of Quickbar

/*CREATIVE HEIGHT --------------- Initial display height (in pixels) of the  gadget */
var GadgetHeight = new Array();
GadgetHeight[0] = 275;  //Full Gadget
GadgetHeight[1] = 189;   //Video of Quickbar
GadgetHeight[2] = 24;   //Music of Quickbar
GadgetHeight[3] = 122;   //Profile of Quickbar
GadgetHeight[4] = 189;   //Photo of Quickbar

//-------------------------------------------GLOBAL VARIABLES-------------------------------------------/
var __is_ff = (navigator.userAgent.indexOf("Firefox") != -1); //Firefox
var ServerHost = "http://gaze.live.net/";
var isGadgetPined = true;
var isShowing = false;
var sEntityName; //Entity Name as input of silverlight control
var nCategoryID; //the type of entity, 1:famous, 2:location, 3:product, etc
var divGadget;
var sl_width = GadgetWidth[0], sl_height = GadgetHeight[0]; // the size of silverlight control
var gadgetStyle;
var miniType = 0; //0:full gadget, 1:video of quickbar, 2:music of quickbar, 3:Info of quickbar, 4:photo of qucikbar
var isSwitch;
var linkRef; // the element of entity or quickbar icons
var hideID; //hanlder id for hide gadget
var showID; //hanlder id for show gadget
var GadgetCloseType;
var isFirstTimeLoad = true;
//----------------------Below variables must be initialized in host page -------------------------------/
var customizedSiteID;
var idPrefix = "ctl00_PageBody_";
var xapRelativePath;

//-------------------------------DHTML style and property change functions------------------------------/
function changeStyle(objectID, propertyName, propertyValue) {
    document.getElementById(objectID).style[propertyName] = propertyValue;
}
function changeProperty(objectID, propertyName, propertyValue) {
    document.getElementById(objectID)[propertyName] = propertyValue;
}
function getStyleValue(objectID, propertyName) {
    return document.getElementById(objectID).style[propertyName];
}
function getPropertyValue(objectID, propertyName) {
    return document.getElementById(objectID)[propertyName];
}
function getObjectValue(objectID) {
    if (document.getElementById(objectID)) {
        return document.getElementById(objectID).value;

    }
    else
        return "";
}

//------------------------------------------------------------------------------------------------------/
window.onbeforeunload = function() {
    try {
        //alert(event);
        if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
            //alert("Closing Page")
            if (isShowing == true) {
                GadgetCloseType = 6;
                HideGaget();
            }
        }
        else {
            //alert("Refresh Page")
            if (isShowing == true) {
                GadgetCloseType = 8;
                HideGaget();
            }
        }
    }
    catch (e) {
        //alert("");
    }
};

//-----------------------------------Match Progress----------------------------------------------------/
window.onload = function() {
    var divIDs = "";
    var arrResaDivs = document.getElementsByTagName("div");

    // Scan all the divs that need to match
    for (var i = 0; i < arrResaDivs.length; i++) {
        var divid = arrResaDivs[i].id;
        var pamara = new RegExp("^D+[a-zA-Z0-9]+[A-Fa-f0-9]{8}([A-Fa-f0-9]{4}){3}[A-Fa-f0-9]{12}$");
        var flag = pamara.test(divid);
        if (flag) {
            customizedSiteID = divid.substring(2, divid.length);
            divIDs += divid + "|";
        }
    }

    if (divIDs) {
        var script = document.createElement('SCRIPT');
        var blogurl = document.location.href;

        var src = ServerHost + "GetHtml.ashx?divid=" + divIDs + "&blogurl=" + blogurl + "&siteid=" + customizedSiteID + "&content="; // +oriContent;
        script.src = src;
        document.body.appendChild(script);
    }
};

function setErrorDivContent(id, html) {
    html = html.replace(/&apos;/g, "'");
    //document.getElementById(id).innerHTML = html;
}

function setDivContent(id, html) {
    html = html.replace(/&apos;/g, "'");

    if (!document.getElementById("divInputs"))// Avoid adding PopUpGadget repeatedly
    {
        html += "<div id=\"divInputs\" style=\"display:none;\" >";
        html += "</div>";
    }
    document.getElementById(id).innerHTML = html;
}

function setInputs(inputs) {
    inputs = inputs.replace(/&apos;/g, "'");

    if (!document.getElementById("divInputs"))// Avoid adding divInputs repeatedly
    {
        inputs += "<div id=\"divInputs\" style=\"display:none;\" >";
        inputs += "</div>";
    }
    if (document.getElementById("divInputs") != null)
        document.getElementById("divInputs").innerHTML = inputs;

    if (getObjectValue("gadgetstyle") == "InPage" && document.getElementById("PopUpGadget")) {
        setCookie("BGSize", 1, "", "", "", "");
        document.getElementById("GadgetScale").value = "1";
        var restricCode = document.getElementById("GadgetRestrictions").value;
        restricCode = restricCode[0] + "|0|" + restricCode[4] + "|0|0|" + restricCode[restricCode.length - 1];
        document.getElementById("GadgetRestrictions").value = restricCode;
    }
    else {
        var div = document.getElementById("divInputs").parentNode;
        var html = div.innerHTML + "<div id=\"PopUpGadget\" style=\"position:absolute; overflow: hidden; z-index:10000; display:none; width:275px; height:275px;\"";
        html += "onmouseover=\"PopUpGadget_onmouseover();\" onmouseout=\"PopUpGadget_onmouseout()\">";
        html += "</div>";
        div.innerHTML = html;
    }
}

//-------------------------------------Display Gadget---------------------------------------------------/
function Cue_onmouseover(entityname, categoryid, obj) {
    isSwitch = miniType > 0 ? true : false;
    document.getElementById("GadgetStartType").value = 1;
    linkRef = obj;
    ActiveGadget(entityname, categoryid, 0);
}

function Cue_onclick(entityname, categoryid, obj) {
    isSwitch = miniType > 0 ? true : false;
    document.getElementById("GadgetStartType").value = 2;
    linkRef = obj;
    ActiveGadget(entityname, categoryid, 0);
}

function QuickbarIcon_onclick(entityname, categoryid, minitype, obj) {
    isSwitch = miniType == 0 ? true : false;
    document.getElementById("GadgetStartType").value = 2;
    linkRef = obj;
    ActiveGadget(entityname, categoryid, minitype);
}

function Cue_onmouseout() {
    clearTimeout(showID);
    if (isGadgetPined)
        return;
    

    GadgetCloseType = 4;
    HideGaget();
}

function ActiveGadget(entityname, categoryid, minitype) {
    clearTimeout(hideID);

    //if the Gadget is already visible, don't relaunch
    if (isShowing && sEntityName == entityname)
        return;

    miniType = minitype;
    sEntityName = entityname;
    nCategoryID = categoryid;

    showID = setTimeout(ShowGadget, DelayInterval);
}

function ShowGadget() {
    isShowing = true;
    divGadget = document.getElementById("PopUpGadget");
    if (!divGadget && getObjectValue("gadgetstyle") == "InPage") {
        alert('It seems that you are using "Inpage" mode, but forget to put the gadget div to your html');
        return;
    }
    setHostDivScale(GadgetWidth[miniType], GadgetHeight[miniType]);


    try {
        var slControl = document.getElementById("GedgetControl");
        if (slControl == null)
            CreateGadget();
        else {
            if (isSwitch) { // if the gadget switchs between quickbar mode and full gadget mode.
                divGadget.innerHTML = "";
                CreateGadget();
            }
            else {// if Gadget has been displayed
                changeStyle("PopUpGadget", "display", "");
                slControl.content.GadgetRoot.Update(sEntityName, miniType);
            }
        }
    } catch (e) {
        CreateGadget();
    }

    SetGagetPostion();
    //clear ShowID
    clearTimeout(showID);
}

function CreateGadget() {
    var InitParams = "EntityName=" + sEntityName;
    if (miniType != null && miniType != "undefined")
        InitParams += ",MiniType=" + miniType;
    var GadgetHtml = "";

    GadgetHtml += "            <div id=\"gadget\" style=\"width: 100%; height: 100%; border:solid 0px gray; \">";
    GadgetHtml += "                <object id=\"GedgetControl\" data=\"data:application/x-silverlight,\" type=\"application/x-silverlight-2\"";
    GadgetHtml += "                    width=\"100%\" height=\"100%\">";

    switch (nCategoryID.toString()) {
        case '1': //1	Celebrity
            if (miniType > 0)
                GadgetHtml += "                    <param name=\"source\" value=\"" + ServerHost + "ClientBin/RESAQuickbar.xap\" />";
            else
                GadgetHtml += "                    <param name=\"source\" value=\"" + ServerHost + "ClientBin/RESAPeopleEntity.xap\" />";
            break;
        case '2': //2	Product
            if (miniType > 0)
                GadgetHtml += "                    <param name=\"source\" value=\"" + ServerHost + "ClientBin/RESAQuickbar.xap\" />";
            else
                GadgetHtml += "                    <param name=\"source\" value=\"" + ServerHost + "ClientBin/RESAProductEntity.xap\" />";
            break;
        case '3': //3	Location
            break;
        case '4': //4	Game
            break;
        case '5': //5	Business
            if (miniType > 0)
                GadgetHtml += "                    <param name=\"source\" value=\"" + ServerHost + "ClientBin/RESAQuickbar.xap\" />";
            else
                GadgetHtml += "                    <param name=\"source\" value=\"" + ServerHost + "ClientBin/RESABusinessEntity.xap\" />";
            break;
        default:
            // alert("Invaild Gaget Type:" + nCategoryID);
            return;
    }

    GadgetHtml += "                    <param name=\"background\" value=\"Transparent\" />"; //Transparent
    GadgetHtml += "                    <param name=\"InitParams\" value=\"" + InitParams + "\" />";
    GadgetHtml += "                    <param name=\"minRuntimeVersion\" value=\"2.0.31005.0\" />";
    GadgetHtml += "                    <param name=\"Windowless\" value=\"True\" />";
    GadgetHtml += "                    <param name=\"autoUpgrade\" value=\"true\" />";
    GadgetHtml += "                    <param name=\"EnableHtmlAccess\" value=\"true\"/>";
    GadgetHtml += "                    <a href=\"http://go.microsoft.com/fwlink/?LinkID=124807\" style=\"text-decoration: none;\">";
    GadgetHtml += "                        <img src=\"http://go.microsoft.com/fwlink/?LinkId=108181\" alt=\"Get Microsoft Silverlight\"";
    GadgetHtml += "                            style=\"border-style: none\" />";
    GadgetHtml += "                    </a>";
    GadgetHtml += "                </object>";
    GadgetHtml += "            </div>";

    divGadget.innerHTML = GadgetHtml;
    changeStyle("PopUpGadget", "display", "");
}

function PopUpGadget_onmouseover() {
    clearTimeout(hideID);
    changeStyle("PopUpGadget", "display", "");
}

function PopUpGadget_onmouseout() {
    if (miniType > 0 || isGadgetPined)
        return;

    clearTimeout(showID);
    GadgetCloseType = 4;
    HideGaget();
}

//----------------------------------------Caculate the Gadget Position--------------------------------------------/
function getScrollY() {
    if (window.pageYOffset != null) {
        return window.pageYOffset;
    } else {
        return document.body.scrollTop;
    }
}

function getScrollX() {
    if (window.pageXOffset != null) {
        return window.pageXOffset;
    } else {
        return document.body.scrollLeft;
    }
}

function SetGagetPostion() {
    var PopUpGadgetWidth = parseInt(GadgetWidth[miniType]);
    var PopUpGadgetHeight = parseInt(GadgetHeight[miniType]);
    //-- alert("tt" + linkRef);
    var pos = getPosition(linkRef);
    var linkPosX = pos.x + GadgetXOffset; //gadget on the right of entity defaultly
    var linkPosY = pos.y + GadgetYOffset; //gadget below entity defaultly

    //Account for page scrolling. Reposition tooltip as neccesary
    if ((getScrollX() + document.body.clientWidth) < (linkPosX + PopUpGadgetWidth)) {
        var tempOffset = (linkPosX + PopUpGadgetWidth) - (getScrollX() + document.body.clientWidth);
        linkPosX -= tempOffset + 6; //6 is the distance between gadget right border with browser border.
    }

    if ((getScrollY() + document.body.clientHeight) < (linkPosY + PopUpGadgetHeight)) {
        linkPosY -= PopUpGadgetHeight + 2 * GadgetXOffset;
    }

    //Make it happen
    linkPosX = linkPosX > 0 ? linkPosX : 0;
    linkPosY = linkPosY > 0 ? linkPosY : 0;
    var linkPosXString = linkPosX + "px";
    var linkPosYString = linkPosY + "px";

    if (!isGadgetPined || isFirstTimeLoad || miniType > 0) {
        changeStyle('PopUpGadget', 'left', linkPosXString);
        changeStyle('PopUpGadget', 'top', linkPosYString);
        isFirstTimeLoad = false;
    }
}
//----------------------------------------Gadget Events-------------------------------------------------/
function PinClick() {
    isGadgetPined = !isGadgetPined;
}

function CloseClick() {
    GadgetCloseType = 5;
    clearTimeout(hideID);
    GadgetDelay();
}

function HideGaget() {
    clearTimeout(hideID);
    hideID = setTimeout(GadgetDelay, DelayInterval);
}

function GadgetDelay() {
    try {
        var slControl = document.getElementById("GedgetControl");
        if (slControl != null && slControl != undefined)
            slControl.content.GadgetRoot.Close(GadgetCloseType);
    }
    catch (e) {
        //alert("Tracking error, please update page to try it again.");
    }

    var divGadget = document.getElementById("PopUpGadget");
    changeStyle("PopUpGadget", "width", "1px");
    changeStyle("PopUpGadget", "height", "1px");
    isShowing = false;

    //clear ID
    clearTimeout(hideID);
}

//-----------------------------Script used to be invioked by silverlight-------------------------------/
//Get the gadget's location left
function getGadgetLocationX() {
    var LocationX = 0;
    var gadget = document.getElementById("PopUpGadget");
    if (gadget != null) {
        LocationX = gadget.style.posLeft < 0 ? 0 : gadget.style.posLeft;
        LocationX = gadget.style.posLeft > screen.width ? screen.width : gadget.style.posLeft;
    }

    return LocationX;
}

//Get the gadget's location top
function getGadgetLocationY() {
    var LocationY = 0;
    var gadget = document.getElementById("PopUpGadget");
    if (gadget != null) {
        LocationY = gadget.style.posTop < 0 ? 0 : gadget.style.posTop;
        LocationY = gadget.style.posTop > screen.height ? screen.height : gadget.style.posTop;
    }
    return LocationY;
}

//Get the system language
function getOSLanguage() {
    return navigator.systemLanguage;
}

//Get the user's screen resolution width
function getResolutionX() {
    return screen.width;
}

//Get the user's screen resolution height
function getResolutionY() {
    return screen.height;
}

function getGadgetPinCheck() {
    return isGadgetPined;
}

function getSiteID() {
    return customizedSiteID;
}

function getLearnMoreUrl() {
    return getObjectValue("LearnMoreUrl");
}

function getNavagationBar() {
    return getObjectValue("NavgationBar");
}

function setFullGadgetWidth(width, height) {
    GadgetWidth[0] = width;
    GadgetHeight[0] = height;
}

function SetPinTrue() {
    isGadgetPined = true;
}

function setPinFalse() {
    isGadgetPined = false;
}

function setHostDivScale(width, height) {
    if (!isShowing) return;

    if (divGadget == null || divGadget == "undefined")
        divGadget = document.getElementById("PopUpGadget");
    divGadget.style.width = width + "px";
    divGadget.style.height = height + "px";
}

function getANID() //read cookies
{
    var search = "ANON=";
    var value = "";
    if (document.cookie.length > 0) {
        var offset = document.cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            var end = document.cookie.indexOf("; ", offset);
            if (end == -1)
                end = document.cookie.length;

            value = unescape(document.cookie.substring(offset, end));
        }

    }
    if (value != "") {
        var bANID = value.indexOf("=", 0);
        var eANID = value.indexOf("&", 0);
        if ((bANID != -1) && (eANID != -1)) {
            value = unescape(value.substring(bANID + 1, eANID));
        }
        else {
            value = "";
        }
    }
    return value;
}

setCookie = function(name, value, expireDays, path, domain, secure) {
    var expires = new Date();
    expires.setTime(expires.getTime() + expireDays * 24 * 3600 * 1000);
    var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
    document.cookie = curCookie;
};

var getPosition = function(element) {
    var valueT = 0, valueL = 0;
    do {
        valueT += element.offsetTop  || 0;
        valueL += element.offsetLeft || 0;
        element = element.offsetParent;
        if (element) {
            if (element.tagName.toUpperCase() == 'BODY') break;
            var p = this.getStyle(element, 'position');
            if (p !== 'static') break;
        }
    } while (element);
    return {x: valueL, y: valueT};
};

camelize = function(style) {
    var parts = style.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = style.charAt(0) == '-'
    ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
    : parts[0];

    for (var i = 1; i < len; i++)
        camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
}

getStyle = function(element, style) {
    style = style == 'float' ? 'cssFloat' : camelize(style);
    var value = element.style[style];
    if (!value || value == 'auto') {
        var css;
        if (document.defaultView) css =  document.defaultView.getComputedStyle(element, null); else css = element.currentStyle;
        value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
}
