var _comboLoaded = false; // only load the combo box once when the page loads

var _BROWSE_BUTTON_ID = "dw_browse_bottom_button";
var _TICK_FLAG = "$t";

// search box ids
var _SELECTBOX_ONE = "slSearchone";
var _SELECTBOX_TWO = "slSearchtwo";
var _SELECTBOX_THREE = "slSearchthree";

// search symbols indicating that the search is to be performed on the
// full list of certain content types
var _SEARCH_ALLRT = "rt_az";
var _SEARCH_ALLTT = "mus_az";
var _SEARCH_ALLGAME = "gm_az";

var _config={ 
    "hometabcontent"  : { id : "hometabcontent", url:"/mcdp.aspx?serviceid={0}&id={1}&type={2}&$t"},
    "msntabcontent"   : { id : "msntabtabcontent", url:"/mcdp.aspx?serviceid={0}&id={1}&type={2}"},
	"small_tabs_content" : { id : "small_tabs_content",url:"/mcdp.aspx?serviceid={0}&lid={1}&type={2}"},
	"dw_test"         : { id : "mcdpKey",url:"/mcdp.aspx?serviceid={0}&p={1}"},
	"dwSearchAll"     : { id : "dwSearchAll",url:"/mcdp.aspx?serviceid={0}"},
	"dwSearchTwo"     : { id : "dwSearchTwo",url:"/mcdp.aspx?serviceid={0}&ctype={1}"},
	"dw_top_iconList" : { id : "dvSearchTwo",url:"/mcdp.aspx?serviceid=dw_top_iconList&lid={0}"},
	"dw_tc_ringtones" : { id : "dw_tc_ringtones",url:"/mcdp.aspx?serviceid=dw_tc_ringtones&n={0}"},
	"dwSearchthree"   : { id : "dwSearchthree",url:"/mcdp.aspx?serviceid={0}&type={1}&genre={2}"},
	"dwSearchRing"   	: { id : "dwSearchRing",url:"/mcdp.aspx?serviceid={0}&s={1}"},
	"AZRingtone"   	  : { id : "AZRingtone",url:"/mcdp.aspx?serviceid={0}&s={1}"},
	"AZTruetone"   	  : { id : "AZTruetone",url:"/mcdp.aspx?serviceid={0}&s={1}"},
	"AZPoly"		  : { id : "AZPoly",url:"/mcdp.aspx?serviceid={0}&s={1}"},
	"AZPolyRes"		  : { id : "AZResults",url:"/mcdp.aspx?serviceid={0}&cat={1}"},
	"AZRingtoneRes"	  : { id : "AZResults",   url:"/mcdp.aspx?serviceid={0}&cat={1}"},
	"AZTruetoneRes"	  : { id : "AZResults",   url:"/mcdp.aspx?serviceid={0}&cat={1}"},
	"AZResults"		  : { id : "AZResults",   url:"/mcdp.aspx?serviceid={0}&cat={1}"},
	"phoneList"       : { id : "phonelist",   url:"/mcdp.aspx?serviceid={0}&ma={1}"},
	"prevbuycore"     : { id : "prevbuycore", url:"/previewbuycore.aspx?cid={1}"}
};

// base helper functions
String.prototype.format = function()
{
	var s = this;

	for (var i=0; i < arguments.length; i++)
	{
		s = (arguments[i] == null) ? s.replace("{" + (i) + "}", "") : s.replace("{" + (i) + "}", arguments[i]);
	}

	return(s);
};

String.prototype.trim = function()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

//use for Pagination
showPageElements=function(a,b,p)
{
	var _container=document.getElementById("dwSearchResult");
	_find="p" + p + "-";
	var divs = _container.getElementsByTagName("div"); 

	for (var i = 0; i < divs.length; i++)
	{ 
		if (divs[i].id.indexOf(_find) >= 0)
			divs[i].style.display="block";
		else
			divs[i].style.display="none";
	}
}

reloadTab = function(cfgIf, targetId, id, type, tab, tabTotal, tabPrefixId)
{
    var reloadFlag = false;

    // Show/Hide tab
    for (var i = 1; i <= tabTotal; i++)
    {
        var handle = document.getElementById(tabPrefixId + i);

        if (!handle) { continue; }

        if (i == tab)
        {
            reloadFlag = (handle.style.display == "none");
        }

        handle.style.display = (i == tab) ? "inline" : "none";
    }

    if (reloadFlag) 
    { 
        reloadContent(cfgIf, targetId, id, type); 
    }
}

loadListBox = function()
{
    var _op = arguments[0];
    var _value = arguments[3];
    var type = "";
    var url = "";
    var configId = "";
    var targetId = "";
    var _objSelect = null;

    switch(_op)
    {
        case 'one':
            // display all the Ringtones
            _objSelect = document.getElementById(_SELECTBOX_THREE);

            if (_objSelect)
            {
                document.getElementById(_SELECTBOX_THREE).innerHTML = "";
                _objSelect=null;
            }

            if (_value == 'all')
            {
                reloadContent('dwSearchRing','dwSearchTwo',_value);
            } else
            {
                configId = "dwSearchTwo";
                targetId = "dwSearchTwo";
                url = _config[configId].url.format(_config[configId].id, _value);
                loadDoc(url, createCallback(loadListBoxCallBack, "one", targetId, false));
            }

            break;
        case 'two':
            targetId = "dwSearchthree";
            _objSelect = document.getElementById(_SELECTBOX_ONE);

            if (_objSelect)
            {
                type = _objSelect.value;
            }

            if (_value == _SEARCH_ALLRT)
            {
                configId = "AZRingtone";
                url = _config[configId].url.format(_config[configId].id, _value);
                switchSearchButton(_BROWSE_BUTTON_ID, false);
                loadDoc(url, createCallback(loadListBoxCallBack, "two", targetId, true)); // indicate A-Z ringtone
            } else if (_value == "gm_az")
            {   // no need to search, there are no level 2 categories for games
                switchSearchButton(_BROWSE_BUTTON_ID, true);
            } else if (_value == "mus_az")
            {
                configId = "AZTruetone";
                url = _config[configId].url.format(_config[configId].id, _value);
                loadDoc(url, createCallback(loadListBoxCallBack, "two", targetId, false));
            } else
            {
                configId = "dwSearchthree";

                if (type == "all") // 'all' means all Ringtones
                {
                    type = "";
                }

                url = _config[configId].url.format(_config[configId].id, type, _value);
                loadDoc(url, createCallback(loadListBoxCallBack, "two", targetId, false));
            }

            break;
        case 'three':
            _objSelect = document.getElementById(_SELECTBOX_THREE);
            switchSearchButton(_BROWSE_BUTTON_ID, true);
            break;
    }
}

function loadListBoxCallBack(boxId, targetId, isAZ, xHtml)
{
	var _objDiv = document.getElementById(targetId);
	_objDiv.innerHTML = xHtml;
	update_combo(targetId);
	_objDiv = null;

    // disable search on the first box, enable search on second and third box
    if (boxId == "one")
    {
        handle = document.getElementById(_SELECTBOX_TWO);
        var switchFlag = (handle && (handle.selectedIndex > -1));
        var genreVal = handle.value;
        handle = document.getElementById(_SELECTBOX_THREE);

        if (switchFlag && handle && (handle.selectedIndex == -1))
        {   // the third box is empty, try to reload it with contents
            loadListBox('two', 'dwSearchthree', 'dwSearchthree', genreVal);
        }
        
        switchSearchButton(_BROWSE_BUTTON_ID, switchFlag);
    } else if (((boxId == "two") && (!isAZ)) || boxId == "three")
    {
        switchSearchButton(_BROWSE_BUTTON_ID, true);
    }
}

var _SEARCHBTN_ON_NAME = "dw_browse_bottom_button";
var _SEARCHBTN_OFF_NAME = "dw_browse_bottom_button_off";

function switchSearchButton(buttonId, enableFlag)
{
    var handle = document.getElementById(buttonId);

    if (!handle) { return; }

    if (enableFlag)
    {   // check if button is switched on already, cannot merge the if above
        if (handle.className != _SEARCHBTN_ON_NAME)
        {
            addEvent(handle, "click", getResults);
            handle.className = _SEARCHBTN_ON_NAME;
        }
    } 
    if (!enableFlag)
    {
        if (handle.className != _SEARCHBTN_OFF_NAME)
        {
            removeEvent(handle, "click", getResults, true);
            handle.className = _SEARCHBTN_OFF_NAME;
        }
    }
}

// function void reloadContent(String[] arguments)
// String configId, String targetId, String() parameters

reloadContent = function()
{
    if (arguments.length < 2) { return; }
 
    var configId = arguments[0];
    var targetId = arguments[1];
 
    // minimum input of two parameters
    if (arguments.length == 2)
    {
        _url = _config[configId]["url"].format(_config[configId]["id"]);
        loadDoc(_url, createCallback(update_content, targetId));
        return;
    }
 
    var args = [];
    if (!_config[configId])
      return;
    args.push(_config[configId]["id"]);
 
    // additional parameters for the url is passed
    for (var i = 2; i < arguments.length ; i++)
    { 
        args.push(arguments[i]);
    }
    string="";
    _url = string.format.apply(_config[configId]["url"], args);

    if (_url.indexOf(_TICK_FLAG) > -1)
    {
        var dateObj = new Date();
        _url = _url.replace(_TICK_FLAG, "t=" + dateObj.getTime())
    }

    loadDoc(_url, createCallback(update_content, targetId));
}

reloadtableContent=function(targetId,idValue)
{
    var _objTarget = document.getElementById(targetId);
	_url=_config[targetId]["url"].format(idValue);
	loadDoc(_url, createCallback(update_content, targetId));
}
reloadIconList=function(idValue,targetId)
{
    var _objTarget=document.getElementById(targetId);
	_url=_config[targetId]["url"].format(idValue);
	loadDoc(_url, createCallback(update_content, targetId));
}

reloadSb=function(obj,targetId)
{
  _objTarget=document.getElementById(targetId);
	_url=_config[targetId]["url"].format(obj.value);
	loadDoc(_url, createCallback(update_content, targetId));
}
function loadDoc(url, fnc)
{
	var xmlhttp;
	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange = createCallback(xmlhttpChange, xmlhttp, fnc);
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}
	else if (window.ActiveXObject)
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
		if (xmlhttp)
		{
			xmlhttp.onreadystatechange = createCallback(xmlhttpChange, xmlhttp, fnc);
			xmlhttp.open("GET",url,true);
			xmlhttp.send();
		}
	}
}

function createCallback(fnc)
{
	var args = [];
	for(var i=1; i < arguments.length; i++)
	{
		args.push(arguments[i]);
	}		
	return function()
	{
		for(var i=0; i < arguments.length; i++)
		{
			args.push(arguments[i]);
		}			
	return fnc.apply(undefined, args);
	}
}

function xmlhttpChange(xmlhttp, fnc)
{
	if (xmlhttp.readyState==4)
	{
		if (xmlhttp.status==200)
		{
			fnc(xmlhttp.responseText);
		}
		else
		{
			fnc();
		}
	}
}

// automatically selects the correct value in each of the three
// combo boxes with the choice the user made last time
update_combo = function(id_div)
{
    if (_comboLoaded) { return; }

    var handle = document.getElementById(_SELECTBOX_ONE);

    if (!handle) { return; }

    qs = new Querystring(location.href);

    if (qs["one"] && (qs["one"].length > 0))
    {
        handle.value = qs["one"];
    }

    handle = document.getElementById(_SELECTBOX_TWO);
    
    if (!handle) 
    {
        _comboLoaded = true;
        return; 
    }

    if (qs["two"] && (qs["two"].length > 0))
    {
        handle.value = unescape(qs["two"]);
    }

    handle = document.getElementById(_SELECTBOX_THREE);
    
    if (!handle) 
    {
        _comboLoaded = true;
        return; 
    }

    if (qs["category"] && (qs["category"].length > 0))
    {
        handle.value = unescape(qs["category"]);
    }

    _comboLoaded = true;
}
update_content = function(id_div, xhtml) {
	var _objDiv = document.getElementById(id_div);
	_objDiv.innerHTML=xhtml;
	update_combo(id_div);
	_objDiv=null;
}
