var _pageLoaded = false; // indicate if the page load functions are called

// required by the handset overlay
var _HANDSETMSG_ID = "dw_showphone";
var _HANDSETLNK_ID = "select-phone-lnk";
var _COOKIE_ID = "9msn_deviceid";
var _CONTENT_INFO_ID = "content-info";
var _HO_BRAND = 1;
var _HO_MODEL = 2;
var _HO_UAIND = 3;
var _HO_RTONEIND = 4;
var _COOKIE_ARRAY_LENGTH = 6;
var _PAGETITLEID = "page_titletxt";
var _MOBILISE_SITENAME = "mobilise";

// send sms messages
var _MSG_INCORRECTNO = "Please enter the phone number in the form of: 04xxxxxxxx.<br /><a class=\"gomobile_tryagain\" href='{0}'>Try again</a>";
var _MSG_INVALIDRESPONSE = "The server is currently busy, please try again later. <a href='{0}'>Try again</a>";
var _MSG_GOMOBILETHANKS = "We have sent you a link. You will receive a SMS soon.<br /> <a class=\"gomobile_tryagain\" href='{0}'>Use this service again</a>.";
var _GOMOBILE_URL = "/gomobile/gomobiledelivery.aspx?_mnum={0}&_msite={1}&z={2}"
var _inputComboHtml = "";

// regular expression for phone number
var _MOBILENO_REG = new RegExp(/^(0|(\+)?61)?4[0-9]{8}$/);

// required by nav highlight function
var _NAV_MOBILISE = "cat_hl_16908";
var _NAV_DOWNLOAD = "cat_hl_84047";

var _smsKeyword = {
    "game"          : "game",
    "wallpaper"     : "pic",
    "sound effects" : "sound",
    "truetone"      : "music",
    "poly"          : "tone" }

/**
Usage:

1.
getDeviceInfoFromCookie(_COOKIE_ID)[_HO_UAIND]

Will return the brand name + model name ua key for filtering games contents.

2.
getDeviceInfoFromCookie(_COOKIE_ID)[_HO_RTONEIND]

Will return the filtering keyword (either 'true' to 'poly') for filtering
ring tone contents.
 */

function showPhoneSelectOverlay()
{
	initPopUp(_HANDSETLNK_ID, 'phonelist.aspx');
}

// for loading the phone list widget when it does not yet exist
function reloadPhoneList(value)
{
    if (value) reloadContent("phoneList", "phonelist-box", value);
}

// for populating the phone list widget once it is loaded
function refreshPhoneList()
{
    var handle = document.getElementById("makerlist");

    if (!handle) { return; }

    handle.selectedIndex = 0;
	showDeviceInfo("deviceinfo", "makerlist", "phonelist");
}

function savePhoneToCookie(phoneInfoArraySerialized)
{
    var cookieVal = new Array();
    var expiryDate = new Date();
    var phoneInfoArray = eval(phoneInfoArraySerialized);

    if (!phoneInfoArray) { return; };

    cookieVal = phoneInfoArray.join("|");
    expiryDate.setHours(expiryDate.getHours() + (24 * 30))
    writeCookie(_COOKIE_ID, cookieVal, expiryDate, "/");
    showDeviceInfo("deviceinfo", "markerlist", "phonelist");
}

function showPreviewBuy(cidVal)
{
    initPopUp('prevbuy_dim', 'previewbuyol.aspx?cid=' + cidVal);
}

function renderPreviewBuy(operateId, containerId, loadId, cidVal)
{
    var qsObj = new Querystring(location.href);

    if (qsObj["cid"] && !cidVal) { cidVal = qsObj["cid"]; }

    var url = "/previewbuycore.aspx?cid=" + cidVal;

    loadDoc(url, createCallback(insertPreviewBuy, containerId, loadId));
}

function insertPreviewBuy(divId, loadId, xHtml)
{
    var handle = null;

    handle = document.getElementById(divId);

    if (!handle) { return; }

    handle.innerHTML = xHtml;

    var deviceInfoArray = getDeviceInfoFromCookie(_COOKIE_ID);

    if (deviceInfoArray)
    {
        phoneListExec('preview');
    }

    handle.style.visibility = "visible";

    if (!loadId) { return; }

    handle = document.getElementById(loadId);

    if (!handle) { return; }
    
    handle.style.display = "none";
    refreshPhoneList();
}

function printSelectedPhoneMsg(resultId, referToParentFlag)
{
    var resultHandle = (referToParentFlag) ? window.parent.document.getElementById(resultId) : document.getElementById(resultId);

    if (!resultHandle) { return; }

    var deviceInfoArr = getDeviceInfoFromCookie(_COOKIE_ID)

    if ((deviceInfoArr == null) || (deviceInfoArr.length == 0)) { return; }

    var msg = "You have selected a {0} {1}".format(deviceInfoArr[_HO_BRAND], deviceInfoArr[_HO_MODEL]);

    if (resultHandle) { resultHandle.innerHTML = msg; }
    
    resultHandle = (referToParentFlag) ? window.parent.document.getElementById(_HANDSETLNK_ID) : document.getElementById(_HANDSETLNK_ID);

    if (resultHandle) { resultHandle.innerHTML = "change phone"; }
}

function previewBuyExec(cmd)
{
    if (!cmd) { return; }

    cmd = cmd.toLowerCase();

    switch(cmd)
    {
        case "close":
            hidePopWin(true);
            break;
        default:
            break;
    }
}

function phoneListExec(cmd)
{
    if (!cmd) { return; }

    cmd = cmd.toLowerCase();

    switch (cmd) 
    {
        case "close":
            printSelectedPhoneMsg(_HANDSETMSG_ID, true);
            hidePopWin(true);
            break;
       case "preview":
            phoneListHighlight('pl-body-', 2, 2);
            refreshPhonePurchase();

            var handle = document.getElementById(_CONTENT_INFO_ID);

            if (!handle) { return; }

            var contentInfoArray = handle.innerHTML;

            if (!contentInfoArray) { return; }

            contentInfoArray = contentInfoArray.replace("\n", "") + ";";
            contentInfoArray = eval(contentInfoArray);

            if ((!contentInfoArray) || (contentInfoArray.length == 0)) { return; }

            var number = "";
            var type = "";
            var subType = "";
            var filter = null;
            var cid = "";

            for (var i = 0; i < contentInfoArray.length; i++)
            {
                if (contentInfoArray[i].length < 2) { continue; }

                if (contentInfoArray[i][0] == "cid")
                {
                    cid = contentInfoArray[i][1];
                } else if (contentInfoArray[i][0] == "id")
                {
                    number = contentInfoArray[i][1];
                } else if (contentInfoArray[i][0] == "content_type")
                {
                    type = contentInfoArray[i][1].toLowerCase();
                } else if (contentInfoArray[i][0] == "filter")
                {
                    filter = contentInfoArray[i][1];
                } else if (contentInfoArray[i][0] == "content_subtype")
                {
                    subType = contentInfoArray[i][1];
                }
            }

            if (isCompatible(type, filter))
            {
                var codeAndNumHandle = document.getElementById("pl-smscode");
                var smsCode = ((type == "sound effects") || (type == "game") || (type == "wallpaper")) ? _smsKeyword[type] : _smsKeyword[filter];
                codeAndNumHandle.innerHTML = smsCode + cid;
                phoneListHighlight('pl-title-', 3, 3);
                phoneListHighlight('pl-dialog-', 3, 3);
            } else
            {
                phoneListHighlight('pl-title-', 2, 3);
                phoneListHighlight('pl-dialog-', 2, 3);
            }

            break;
       default:
            break;
    }
}

function isCompatible(type, filter)
{
    var deviceInfoArray = getDeviceInfoFromCookie(_COOKIE_ID);

    if ((!type) || (!deviceInfoArray) || (deviceInfoArray.length != _COOKIE_ARRAY_LENGTH)) { return false; }

    var clientUA = deviceInfoArray[_HO_UAIND];
    var clientRT = deviceInfoArray[_HO_RTONEIND];

    type = type.toLowerCase();
    clientUA = clientUA.toLowerCase();

    if (type == "wallpaper")
    {
        return true;
    } else if (type == "game")
    {
        if ((!filter) || (!clientUA))  { return false; }

        for (var _i = 0; _i < filter.length; _i++)
        {
            var filterUA = filter[_i].toLowerCase();

            if (filterUA == clientUA) { return true; }
        }
    } else if ((type == "ringtone") || (type == "sound effects") || (type == "realtone"))
    {
        filter = filter.toLowerCase();

        if ((clientRT.trim() == "") || (clientRT == filter)) { return true; }
    }

    return false;
}

function phoneListHighlight(prefix, activeId, range)
{
    for (var i = 0; i < range; i++)
    {
        handle = document.getElementById(prefix + (i + 1));
        handle.style.display = "none";
    }

    handle = document.getElementById(prefix + activeId);
    handle.style.display = "block";
}

function refreshPhonePurchase()
{
    var deviceInfoArray = getDeviceInfoFromCookie(_COOKIE_ID);

    if (!deviceInfoArray) { return; }

    var msg = "{0} {1}".format(deviceInfoArray[_HO_BRAND], deviceInfoArray[_HO_MODEL])
    var handle = document.getElementById("pl-selected-device");
    if (handle) { handle.innerHTML = msg; }
    var handle = document.getElementById("pl-selected-phone");
    var urlReg = /http:\/\/([^/]+)\//

    handle.setAttribute("src", "{0}img/phones/{1}".format(urlReg.exec(document.location)[0], deviceInfoArray[5]));
}

function showDeviceInfo(handleId, brandSelectId, modelSelectId)
{
    // read device and display info
    var handle = document.getElementById(handleId);

    if (!handleId) { return; }

    var childNodesCount = (handle.childNodes) ? handle.childNodes.length : 0;
    var deviceInfoArray = getDeviceInfoFromCookie(_COOKIE_ID);

    if (deviceInfoArray)
    {   // remove previous information if any to make room for selected handset
        for (var i = 0; i < childNodesCount; i++)
        {
            handle.removeChild(handle.childNodes[0]);
        }
    }

    if (!deviceInfoArray || (deviceInfoArray.length < _COOKIE_ARRAY_LENGTH)) { return; }

    var brandName = deviceInfoArray[1];
    var modelName = deviceInfoArray[2];
    var phoneListHandle = document.getElementById(modelSelectId);
    var reloadPhoneListFlag = false;

    selectHighlight(brandSelectId, brandName);

    var modelSelectHandle = document.getElementById(modelSelectId);

    reloadPhoneListFlag = (!modelSelectHandle || (modelSelectHandle.selectedIndex < 0))
    
    if (brandName && reloadPhoneListFlag)
    {
        var configId = "phoneList";
        var args = [];
        args.push(_config[configId]["id"]);
        args.push(brandName.toLowerCase());
        string = "";
        _url = string.format.apply(_config[configId]["url"], args);
        loadDoc(_url, createCallback(populatePhoneList, "phonelist-box", modelSelectId, modelName));
        _handsetOverlayLoaded = true;
    }

    // create the device info block
    var imgNode = document.createElement("img");
    var urlReg = /http:\/\/([^/]+)\//

    imgNode.setAttribute("src", "{0}img/phones/{1}".format(urlReg.exec(document.location)[0], deviceInfoArray[5]));
    handle.appendChild(imgNode);

    return;
}

function populatePhoneList(divId, modelSelectId, modelName, xhtml)
{
	var _objDiv = document.getElementById(divId);
	_objDiv.innerHTML = xhtml;
	update_combo(divId);
	_objDiv = null;
    selectHighlight(modelSelectId, modelName);
}

function selectHighlight(selectId, selValue)
{
    var handle = document.getElementById(selectId);

    if ((handle == null) || (selValue == null)) return;

    for (var i = 0; i < handle.options.length; i++)
    {
        if (handle.options[i].value.toLowerCase().indexOf(selValue.toLowerCase()) == -1) { continue; }

        handle.selectedIndex = i;
        break;
    }
}

function getDeviceInfoFromCookie(cookieId)
{
    var returnVal = {};
    var deviceInfo = readCookie(cookieId);
    var devicePartsReg = /([^|]+)/g;

    if (!deviceInfo) { return; }

    deviceInfo = deviceInfo.replace("||", "| |");
    returnVal = deviceInfo.match(devicePartsReg);

    return returnVal;
}

function showWindow(url,width, height)
{
    window.open(url, 'margin', 
    'toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,status=no,resizable=yes,width=' + width + ',height=' + height);
}

function setArticleBG(imgUrl)
{
    document.getElementById("topicons").style.background = "transparent url(\'" + imgUrl + "\') no-repeat left top";
}

/**
 * This function is responsible for sending sms to the user and print 
 * appropriate message on the target div.
 */
function processSendSms(textBoxId)
{
    var txtBoxHandle = document.getElementById(textBoxId);
    var phoneNo = "";
    var siteName = "";

    if (!txtBoxHandle) { return false; }

    phoneNo = txtBoxHandle.value;

    if (!phoneNo || !phoneNo.match(_MOBILENO_REG))
    {
        var handle = document.getElementById("articleinputcombo");
        _inputComboHtml = handle.innerHTML;
        handle.innerHTML = _MSG_INCORRECTNO.format("javascript:refreshSendSms();");
    } else
    {
        siteName = txtBoxHandle.attributes["name"].value;
        var adParam = ""
        var goMobileUrl = _GOMOBILE_URL.format(phoneNo, siteName, adParam);
        var containerId = textBoxId;
        loadDoc(goMobileUrl, createCallback(sendSmsCallBack, containerId, siteName));
    }

    return false;
}

var _mobileTextBoxId = "txtbx_sendsms";
function mobileKeyHandler(e)
{
    var keyCodeVal = 0;

    if (e && e.which) 
    {
        e = e;
        keyCodeVal = e.which;
    } else
    {
        e = event
        keyCodeVal = e.keyCode;
    }
    
    if (keyCodeVal == 13)
    {
       return processSendSms(_mobileTextBoxId);
    } else
    {
        return true;
    }
}

var _siteNameProductMap = {"mobilise" : "mobilise",
"cleo" : "cleo",
"national nine news" : "news",
"ralph" : "ralph",
"windows live hotmail" : "hotmail",
"windows live messenger" : "messenger",
"windows live search" : "livesearch",
"windows live spaces" : "spaces",
"yourtime movies" : "moviefix",
"yourtime gigs" : "gigs",
"yourtime restaurants" : "restaurants",
"yourtime tv" : "tvfix",
"yourtime bars" : "bars"};

function getProductNameByArticleInput(textBoxId)
{
    var txtBoxHandle = document.getElementById(textBoxId)
    var siteName = txtBoxHandle.attributes["name"].value;
    return _siteNameProductMap[siteName.toLowerCase()];
}

var _GOMOBILE_SUBMIT_KEY = "thanks";

function sendSmsCallBack(containerId, siteName, xHtml)
{
    var errorMsg = "";
    var handle = document.getElementById("articleinputcombo");

    if (!xHtml || (xHtml.indexOf("fail") > -1))
    {
        errorMsg = "<div style='font-weight: bold;'>Sorry</div>";
        errorMsg += "<div>{0}</div>";

        if (xHtml.indexOf("valid mobile number") > -1)
        {
            errorMsg = errorMsg.format(_MSG_INCORRECTNO.format("javascript:refreshSendSms();"));
        } else
        {
            errorMsg = errorMsg.format(_MSG_INVALIDRESPONSE.format("javascript:refreshSendSms();"));
        }

        if (handle)
        {
            _inputComboHtml = handle.innerHTML;
            handle.innerHTML = errorMsg;
        }
    } else
    {
        errorMsg = "<div style='font-weight: bold;'>Thank you.</div>";
        errorMsg += _MSG_GOMOBILETHANKS.format("javascript:refreshSendSms();");
        _inputComboHtml = handle.innerHTML;
        handle.innerHTML = errorMsg;

        var gomobileObj = new mobilise.ninemsn.gomobile();
        gomobileObj.setTrackingUrl(_MOBILISE_SITENAME, _siteNameProductMap[siteName.toLowerCase()], _GOMOBILE_SUBMIT_KEY);
    }
}

function refreshSendSms()
{
    var handle = document.getElementById("articleinputcombo");

    handle.innerHTML = _inputComboHtml;
}

function getFirstElementByTagName(source, tagName)
{
	var handle = null;
    
    if (!source || !source.hasChildNodes()) { return null; }

	for (var _i = 0; _i < source.childNodes.length; _i++)
    {
        if (source.childNodes[_i].tagName == tagName)
        {
            handle = source.childNodes[_i];
            break;
        }
    }

	return handle;
}

function redirectByKey(contentType, sourceId)
{
    var _TYPEGAME = "game";
    var _TYPEWP = "wallpaper";
    var _TYPETONE = "ringtone";

    switch (contentType) 
    {
        case _TYPEGAME:
            location.href = "/download.aspx?sectionid=5911&subsectionid=75041";
            break;
        case _TYPEWP:
            location.href = "/download.aspx?sectionid=5911&subsectionid=75042";
            break;
        case _TYPETONE:
            location.href = "/download.aspx?sectionid=5911&subsectionid=75043";
            break;
        default:
            break;
	}
}

function leftnavHighlight()
{
    _NAV_MOBILISE = "cat_hl_16908";
    _NAV_DOWNLOAD = "cat_hl_84047";

    if (typeof(JS_SUB_SECTIONID) == "undefined") { return; }

    var handle = null;

    if (JS_SUB_SECTIONID == "0")
    {
        var targetList = new Array(_NAV_MOBILISE, _NAV_DOWNLOAD);

        for (var _i = 0; _i < targetList.length; _i++)
        {
            handle = document.getElementById(targetList[_i]);

            if (handle)
            {
                handle = getChildNodeByTagName(handle, "UL");
                handle = getChildNodeByTagName(handle, "LI");
                handle = getChildNodeByTagName(handle, "A");
                handle = getChildNodeByTagName(handle, "IMG");

                if (handle)
                {
                    if (handle.id == ("navimg_" + JS_SECTIONID))
                    {
                        handle.parentNode.style.color = "#FFFFFF";
                        break;
                    }
                }
            }
        }
    } else
    {
        if (!listHighlight(_NAV_MOBILISE, "sub" + JS_SUB_SECTIONID, "selected"))
        {
            listHighlight(_NAV_DOWNLOAD, "sub" + JS_SUB_SECTIONID, "selected");
        }
    }
}

function listHighlight(navId, targetVal, className)
{
    var returnVal = false;
    var handle = document.getElementById(navId);

    if (!handle) { return; }

    handle = getChildNodeByTagName(handle, "UL");

    if (!handle) { return; }

    handle = getChildNodeByTagName(handle, "LI");

    if (!handle) { return; }

    handle = getChildNodeByTagName(handle, "UL");

    if (!handle) { return; }

    for (var _i = 0; _i < handle.childNodes.length; _i++)
    {
        if (handle.childNodes[_i].attributes && handle.childNodes[_i].id && (handle.childNodes[_i].id == targetVal))
        {
            handle = getChildNodeByTagName(handle.childNodes[_i], "A");

            if (handle)
            {
                handle.className = className;
                returnVal = true;
                break;
            }
        }
    }

    return returnVal;
}

function getChildNodeByTagName(node, tagName)
{
    if (!node || (node.childNodes.length == 0)) { return null; }

    for (var _i = 0; _i < node.childNodes.length; _i++)
    {
        if (node.childNodes[_i].tagName == tagName)
        {
            return node.childNodes[_i];
        }
    }

    return null;
}

function leftnav_load()
{
    // re-adjust the height of the menu on load
    var LEFT_NAV_ID = "lftcol";
    var leftCol = document.getElementById(LEFT_NAV_ID);
    var maxHeight = 0;

    leftnavHighlight(); // highlight the selected menu item

    if (leftCol)
    { 
        leftCol.style.height = leftCol.scrollHeight + "px"; 
    }

    if (document.all) { return; }

    var handle = document.getElementById("midcol");

    if (!handle) { return; }

    var height = handle.scrollHeight;
    maxHeight = height;

    // re-adjust the height of the left nav
    handle = document.getElementById(LEFT_NAV_ID);

    if (handle && (handle.scrollHeight < maxHeight))
    {
        handle.style.height = (maxHeight) + "px";
        setHeight("contentcol", maxHeight);
    } else
    {
        maxHeight = handle.scrollHeight;
        setHeight("contentcol", maxHeight);
    }

    handle = document.getElementById("rghtcol");

    if (handle && (handle.scrollHeight < maxHeight))
    {
        handle.style.height = (maxHeight) + "px";
    } else
    {
        setHeight("rghtcol", maxHeight);
    }

    setConHgt();
}

function setHeight(id, height)
{
    var handle = document.getElementById(id);

    if (!handle) { return; }

    handle.style.height = height + "px";
}

var _DEFAULT_SEARCH_HINT = " Search Mobilise";
var _SEARCH_TXTBOX_ID = "txtSearch";

function item_load()
{
    hideOrShow("previewbuycontent", true, false);

    var playerObj = document.getElementById("mediaplayer");

    if (playerObj)
    {
        playerObj = playerObj.parentNode;
        playerObj.style.marginLeft = "51px";
        playerObj.style.display = "block";
        playerObj.style.zIndex = "2000";
    }
}

function searchBox_load()
{
    var handle = document.getElementById(_SEARCH_TXTBOX_ID);
    if (!handle) { return; }

    var qsObj = new Querystring(location.href);

    if (handle && qsObj["query"])
    {
        handle.value = qsObj["query"];
    } else
    {
        handle.value = _DEFAULT_SEARCH_HINT;
    }

    addEvent(handle, "blur", function() {inputOnBlur(_SEARCH_TXTBOX_ID, _DEFAULT_SEARCH_HINT);} )
    addEvent(handle, "focus", function() {inputOnFocus(_SEARCH_TXTBOX_ID, _DEFAULT_SEARCH_HINT);} )
    handle = document.getElementById("frmForm");
    
    if (handle) 
    {
        addEvent(handle, "submit", function() { doSearch('txtSearch'); });
    }
}

/**
 * Refresh the contents of the listBox
 * just executed when the page contains the listbox
 */
search_listBox_refresh=function()
{
  if (! document.getElementById('slSearchone'))
    return;
    qs=new Querystring(location.href);
    _one=qs["one"];
    if (!_one)
      return;    
    document.getElementById('slSearchone').value=qs["one"];
    //update second listbox
    loadListBox('one','dwSearchTwo','dwSearchTwo',_one)
    
    _two=qs["two"];
    if (!_two)
      return;
    //update third listbox
    loadListBox('two','dwSearchthree','dwSearchthree',_two)
    switchSearchButton(_BROWSE_BUTTON_ID, true);
}
/**
 * Put all the global page initialise codes in this 
 * pageLoad() function.
 */
function pageLoad()
{
    leftnav_load();
    searchBox_load();
    //Refresh search ListBox
    search_listBox_refresh();
    printSelectedPhoneMsg(_HANDSETMSG_ID, false);
    _pageLoaded = true;
    overlayInit();
}

addLoadEvent(pageLoad)
