var _urlEncodeMap = {
    "+" : "%252b",
    "&" : "%2526",
    "\"" : "%2522"
};

/**
* GetResults invoke to the search_category.aspx page
*
*/
function getResults()
{
    var selectHandle = document.getElementById("slSearchone");
    var contentTypeVal = ""; // this value is used to highlight the list box
    var genreVal = "";
    var categoryVal = "";
    var selectLvl2 = "";
    var typeVal = ""; // this is not the same as contentTypeVal, for 'All Ringtones' seaches
                      // this value should be set to empty string

    // check if user have selected the first search box
	if (selectHandle.selectedIndex == -1) { return; }
    
    contentTypeVal = selectHandle.value;
    typeVal = contentTypeVal;
	selectHandle = document.getElementById("slSearchtwo");

    // check if user have selected the second search box
	if (selectHandle.selectedIndex == -1) { return; }
    
    genreVal = selectHandle.value; // keep a backup of this value to highlight
    selectLvl2 = genreVal;         // user selection when page loads
	selectHandle = document.getElementById("slSearchthree");

	if (!selectHandle || selectHandle.selectedIndex == -1)
	{   // for content with no category only genre

        if (contentTypeVal == "all")
        {
            typeVal = "";
        }

        if (genreVal == _SEARCH_ALLRT)
        {   // user should not be able to run this query for all *tones
            return;
        } else if ((genreVal == _SEARCH_ALLGAME) || (genreVal == _SEARCH_ALLTT))
        {
            genreVal = "";
        }

        if (contentTypeVal == "")
        {
            location.href = "search_category.aspx?one=" + contentTypeVal + "&two=" + urlDoubleEncode(selectLvl2, _urlEncodeMap) + "&genre=" + 
                        urlDoubleEncode(genreVal, _urlEncodeMap);
        } else
        {
            location.href = "search_category.aspx?one=" + contentTypeVal + "&two=" + urlDoubleEncode(selectLvl2, _urlEncodeMap) + "&type=" + typeVal + "&genre=" + 
                        urlDoubleEncode(genreVal, _urlEncodeMap);
        }
	}
	else
	{   // for content with category
        categoryVal = selectHandle.value;

        if (contentTypeVal == "all")
        {   // user is searching for all ringtones, do not specify type
            if (genreVal && (genreVal.toLowerCase() == _SEARCH_ALLRT))
            {   // user wants to search across all artists, do not specify genre
                genreVal = "";
            }

            location.href = "search_category.aspx?one=" + contentTypeVal + "&two=" + urlDoubleEncode(selectLvl2, _urlEncodeMap) + "&genre=" + genreVal + "&category=" + 
                            urlDoubleEncode(categoryVal, _urlEncodeMap);
        } else
        {
            if ((genreVal == _SEARCH_ALLTT) || (genreVal == _SEARCH_ALLRT))
            {
                genreVal = "";
            }

    		location.href = "search_category.aspx?one=" + contentTypeVal + "&two=" + urlDoubleEncode(selectLvl2, _urlEncodeMap) + "&type=" + contentTypeVal + "&genre=" + genreVal + "&category=" + 
                            urlDoubleEncode(categoryVal, _urlEncodeMap);
        }
	}
}

function urlDoubleEncode(urlArg, encodeMap)
{
    var returnVal = urlArg;

    for (var ch in encodeMap)
    {
        if (urlArg.indexOf(ch) > -1)
        {
            returnVal = returnVal.replace(ch, encodeMap[ch]);
        }
    }

    return returnVal;
}

/*pagination Functions*/
showPageElements = function(divId,p,rangeElements,pages)
{
	var _container = document.getElementById(divId);
	var _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="inline";
		else
		  if(divs[i].id.indexOf("p") >=0)
			  divs[i].style.display="none";
	}

	var _objLinks=document.getElementById(divId + "_links");
	_objLinks.innerHTML=displayPageLinks(divId,p,rangeElements,pages);
	_objLinks.style.display="block";
}

showPageElementsMultiRow = function(divId, p, rangeElements, pages)
{
	var _container = document.getElementById(divId);
	var _find = "p" + p + "-";
	var divs = _container.getElementsByTagName("div");

    var filterReg = new RegExp("^p([0-9]+)");

	for (var _i = 0; _i < divs.length; _i++) 
	{ 
		if (divs[_i].id.indexOf(_find) >= 0)
        {
			divs[_i].style.display="inline";
            if (divs[_i].parentElement) 
            {
                divs[_i].parentElement.style.display="inline";
            } else
            {
                divs[_i].parentNode.style.display="inline";
            }
        } else if (divs[_i].id.length == 0)
        {
            // skip this
        } else if (filterReg.test(divs[_i].id))
        {
    		divs[_i].style.display="none";

            if (divs[_i].parentElement)
            {
                divs[_i].parentElement.style.display="none";
            } else
            {
                divs[_i].parentNode.style.display="none";
            }
        }
	}

    var _objLinks=document.getElementById(divId + "_links");
	_objLinks.innerHTML=displayPageLinksMultiRow(divId,p,rangeElements,pages);
	_objLinks.style.display="inline";
}

displayPageLinks=function(divId,page,rangeElements,pages)
{
	if (pages ==0)
		pages=1;
	var _result="";
	var range=Math.floor((page-1)/rangeElements) +1;
	var _start=getPageRange(range,rangeElements,'start');
	var _end=getPageRange(range,rangeElements,'end');
	if (_end > pages )
		_end=pages;
	if (_start > 1)
		_result+="<a href=\"javascript:showPageElements('" + divId + "'," + (_start-1) + "," + rangeElements + "," + pages + ")\">" + "Previous</a>";

    for(var i=_start;i<=_end;i++)
	{
        if (i == page)
        {
            _result += "<span class=\"pagelink_selected\">" + i + "</span>";
        } else
        {
            _result += "<a href=\"javascript:showPageElements('" + divId + "'," + i + "," + rangeElements + "," + pages + ")\">" + i +"</a>";
        }
	}

	if (_end < pages )
		_result+="<a href=\"javascript:showPageElements('" + divId + "'," + (_end + 1) + "," + rangeElements + "," + pages + ")\">" + "Next</a>";
	return "" + _result;
}

displayPageLinksMultiRow=function(divId,page,rangeElements,pages)
{
	if (pages == 0) { pages=1; }

	var _result="";
	var range=Math.floor((page-1)/rangeElements) +1;
	var _start=getPageRange(range,rangeElements,'start');
	var _end=getPageRange(range,rangeElements,'end');

	if (_end > pages )
		_end=pages;
	if (_start > 1)
		_result+="<a href=\"javascript:showPageElementsMultiRow('" + divId + "'," + (_start-1) + "," + rangeElements + "," + pages + ")\">" + "Previous</a>";

    for (var i = _start; i <= _end; i++)
	{
        if (i == page)
        {
            _result += "<span class=\"pagelink_selected\">" + i + "</span>";
        } else
        {
            _result += "<a href=\"javascript:showPageElementsMultiRow('" + divId + "'," + i + "," + rangeElements + "," + pages + ")\">" + i +"</a>";
        }
	}

	if (_end < pages )
		_result+="<a href=\"javascript:showPageElementsMultiRow('" + divId + "'," + (_end + 1) + "," + rangeElements + "," + pages + ")\">" + "Next</a>";

    return "" + _result;
}


getPageRange=function(range,rangeElements,key)
{
	var _result;
	if (key == 'start')
	{
		_result=rangeElements * (range -1 ) +1;
	}
	else
	{
		_result=rangeElements*(range);
	}
	return _result;
}
/*End of pagination Functions*/

keyhandler = function(e) 
{
    var keyCodeVal = 0;

    if (e && e.which) 
    {
        e = e;
        keyCodeVal = e.which;
    } else
    {
        e = event
        keyCodeVal = e.keyCode;
    }
    
    if (keyCodeVal == 13)
    {
       return doSearch('txtSearch');
    } else
    {
        return true;
    }
}

doSearch = function(searchField)
{
    var _obj = document.getElementById(searchField);
    var _strUrl = "" + _obj.value;
    _strUrl = _strUrl.replace("'", "", "g");
    _strUrl = "search.aspx?collection=MobiliseWeb&query=" + _strUrl;
    window.location.href = _strUrl;
    return false; 
}

// mobilise ninemsn util
function readCookie(name, rawValueFlag)
{
	var strCookie = document.cookie;
    var cookieName = name + "=";
    var ca = strCookie.split(';');

    if (ca == null) { return null; }
    
    for(var i=0;i<ca.length;i++)
    {
        var c = ca[i];

        while (c.charAt(0)==' ') 
        {
            c = c.substring(1,c.length);
        }

        if (c.indexOf(cookieName) == 0) 
        {
            return ((rawValueFlag) ? c : c.substring(cookieName.length,c.length));
        }
    }

    return null;
}

function writeCookie(cookieName, cookieValue, expiryDate, path)
{
    var cookieVal = readCookie(cookieName, true);

	if (!cookieVal)
	{
		var newExpiry;
	    
		if (expiryDate != null || expiryDate != "")
		{
			newExpiry = new Date();
			newExpiry.setYear(newExpiry.getFullYear() + 5);
		} else
		{
			newExpiry = expiryDate;
		}

		if (typeof document!='undefined')
		{
			return (document.cookie = "{0}={1};expires={2};path={3};".format(cookieName, cookieValue, newExpiry.toGMTString(), path));
		}
	} else
	{
		// scan cookie, replace part
		var strNew = "";
		var ca = cookieVal.split(';');

		for (var i = 0; i <ca.length; i++)
		{
			var c = ca[i];
			var cp = c.split("=");
			
			if (cp[0] == cookieName) { cp[1] = cookieValue; }
				
			if (strNew.length > 0) { strNew += ";"; }
				
			strNew += cp[0] + "=" + cp[1];
		}

		return (document.cookie = "{0};expires={1};path={2};".format(strNew, expiryDate.toGMTString(), path));
	}
}

function eraseCookie(cookieName)
{
    var yesterdayDate = new Date();
    yesterdayDate.setDate(yesterdayDate.getDate() - 1);
    writeCookie(cookieName, "", yesterdayDate, "/");
}

function addLoadEvent(func) 
{
	var oldonload = window.onload;

	if (typeof window.onload != 'function') 
    {
		window.onload = func;
	} else 
    {
		window.onload = function() 
        {
			oldonload();
			func();
		}
	}
}

function hideOrShow(id, visibleOrNotDisplay, hideOrNotShow)
{
    var handle = document.getElementById(id);
    if (!handle) { return; }
    
    if (visibleOrNotDisplay) 
    {
        handle.style.visibility = (hideOrNotShow) ? "hidden" : "visible";
    } else
    {
        handle.style.display = (hideOrNotShow) ? "none" : "block";
    }
}


/**
 * X-browser event handler attachment and detachment
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function addEvent(obj, evType, fn)
{
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent)
	{
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else 
	{
		return false;
	}
}
function removeEvent(obj, evType, fn, useCapture)
{
	if (obj.removeEventListener)
	{
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.detachEvent)
	{
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else 
	{
		//alert("Handler could not be removed");
	}
}
/**
 * to work with Opera/Moz (by webmaster at subimage dot com)
 *
 * Gets the full width/height because it's different for most browsers.
 */
function getViewportHeight() 
{
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 
	return window.undefined; 
}
function getViewportWidth() 
{
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
	return window.undefined; 
}

function Querystring(targetUrl)
{
	// get the query string, ignore the ? at the front.
	var querystring = ((targetUrl == null) || (targetUrl == "")) ? location.search.substring(1,location.search.length) : targetUrl;

    if (targetUrl.indexOf("?") == -1) { return; }

	querystring = targetUrl.split('?');
	var args = querystring[1].split('&'); // parse out name/value pairs separated via &

	// split out each name = value pair
	for (var i=0;i<args.length;i++)
	{
		var pair = args[i].split('=');

		// fix broken unescaping
		temp = unescape(pair[0]).split('+');
		name = temp.join(' ');
		temp = unescape(pair[1]).split('+');
		value = temp.join(' ');
		this[name]=value;
	}

	this.Querystring_get = function(strKey, strDefault)
	{
	    var value = this[strKey];

	    if (value == null) { value = strDefault; }

	    return value;
	}
}

function inputOnBlur(id, hint) 
{
    var handle = document.getElementById(id);

    if (!handle) { return; }

	if (handle.value == "") { handle.value = hint; }
}

function inputOnFocus(id, hint) 
{
    var handle = document.getElementById(id);

    if (!handle) { return; }

	if (handle.value == hint) { handle.value = ""; }
}

/**
 * Overlay creation functions begin
 */

var Fload=false;

// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gReturnFunc;
var gPopupIsShown = false;
var gHideSelects = false;

var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");

/**
 * DOM element IDs used by the overlay control.
 */
var _POPCONTAINER_ID = "pop-container";
var _POPTITLE_ID = "pop-title";
var _POPUPFRAME_ID = "popup-frame";

// if using Mozilla or Firefox, use Tab-key trap.
if (document.onkeypress) { document.onkeypress = keyDownHandler; }

/**
 * Initializes popup code on load.	
 */
function initPopUp(elemId, _url)
{
    // Add the HTML to the body
    if (!Fload) { return; }

    var bodyHandle = document.getElementsByTagName('BODY')[0];
    var popcont = document.createElement('div');

    popcont.id = _POPCONTAINER_ID;
    popcont.innerHTML = '<iframe src="" scrolling="no" frameborder="0" id="' + _POPUPFRAME_ID + '" name="' + _POPUPFRAME_ID + '"></iframe>';
    bodyHandle.appendChild(popcont);
    gPopupContainer = document.getElementById(_POPCONTAINER_ID);
    gPopupContainer.style.position = "absolute";
    gPopFrame = document.getElementById(_POPUPFRAME_ID);
	
	// check to see if this is IE version 6 or lower. hide select boxes if so
	// maybe they'll fix this in version 7?
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);

	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1)
	{
		gHideSelects = true;
	}

	var width = 500;
	var height = 200;

	// Parse out optional width and height from className
	params = document.getElementById(elemId).className.split('-');

	if (params.length == 3)
	{
		width = parseInt(params[1]);
		height = parseInt(params[2]);
	} else if (document.all) 
    {
       width = parseInt(params[1]);
	   height = 445;
    } else
    {
       width = parseInt(params[1]);
	   height = 455;
	}

    gPopFrame.style.width = width + "px";
    gPopFrame.style.height = height + "px";    
    showPopWin(_url, width, height, null); // return false; -> used in the future
}

 /**
	* @argument width - int in pixels
	* @argument height - int in pixels
	* @argument url - url to display
	* @argument returnFunc - function to call when returning true from the window.
	* @argument showCloseBox - show the close box - default true
	*/

function showPopWin(url, width, height, returnFunc, showCloseBox) 
{
	gPopupIsShown = true;
	disableTabIndexes();
	gPopupContainer.style.display = "block";
	centerPopWin(width, height); // calculate where to place the window on screen
	gPopFrame.src = url; // set the url
	gReturnFunc = returnFunc;
}

function centerPopWin(width, height) 
{
    if (!gPopupIsShown) { return; }

	if (width == null || isNaN(width))
    {
        width = gPopupContainer.offsetWidth;
    }

    if (height == null) 
    {
        height = gPopupContainer.offsetHeight;
    }
    
    var bodyHandle = document.getElementsByTagName("BODY")[0];
    var fullHeight = getViewportHeight();
    var fullWidth = getViewportWidth();

    _hdHeigth = fixPosition();
    //gPopupContainer.style.top = (_hdHeigth + ((fullHeight - height) / 2)) + "px";
    //gPopupContainer.style.top = (_hdHeigth + (fullHeight / 2)) + "px";
    gPopupContainer.style.top = (_hdHeigth + ((fullHeight - height) / 2) + f_scrollTop()) + "px";
    gPopupContainer.style.left =  ((fullWidth - width) / 2) + "px";
}

function f_scrollTop()
{
	return window.pageYOffset ? window.pageYOffset : 
        (document.documentElement ? document.documentElement.scrollTop : 
		(document.body ? document.body.scrollTop : 0));
}

addEvent(window, "resize", centerPopWin);
window.onscroll = centerPopWin;

/**
 * Sets the size of the popup mask.
 *
 */
function setMaskSize()
{
	var theBody = document.getElementsByTagName("BODY")[0];
			
	var fullHeight = getViewportHeight();
	var fullWidth = getViewportWidth();
	
	// Determine what's bigger, scrollHeight or fullHeight / width
	if (fullHeight > theBody.scrollHeight) 
	{
		popHeight = fullHeight;
	} 
    else
	{
		popHeight = theBody.scrollHeight;
	}
	
	if (fullWidth > theBody.scrollWidth)
	{
		popWidth = fullWidth;
	} else
	{
		popWidth = theBody.scrollWidth;
	}

	gPopupMask.style.height = popHeight + "px";
	gPopupMask.style.width = popWidth + "px";
	
	//Fix white space in IE
	if (navigator.appName.indexOf('Microsoft') != -1)
	{
		gPopFrame.style.height = "400px";
		if (window.parent.document.location.href.indexOf("ninemsn") < 0) { document.getElementById("popupTitleBar").style.width="733px"; }
	}
}

/**
 * @argument callReturnFunc - bool - determines if we call the return function specified
 * @argument returnVal - anything - return value 
 */
function hidePopWin(insideIFrame, callReturnFunc)
{
	var theBody = document.getElementsByTagName("BODY")[0];

	gPopupIsShown = false;
	theBody.style.overflow = "";
	restoreTabIndexes(insideIFrame);
	
	if (!gPopupContainer) { gPopupContainer = (insideIFrame) ? window.parent.document.getElementById(_POPCONTAINER_ID) : document.getElementById(_POPCONTAINER_ID); }

	gPopupContainer.style.display = "none";

	if ((callReturnFunc == true) && (gReturnFunc != null))
    {
		gReturnFunc(window.frames[_POPUPFRAME_ID].returnVal);
	}

	if (!gPopFrame) { gPopFrame = (insideIFrame) ? window.parent.document.getElementById(_POPUPFRAME_ID) : document.getElementById(_POPUPFRAME_ID); }
	
	gPopFrame.src = "";

	// display all select boxes
	if (gHideSelects) { displaySelectBoxes(); }

	removeNode(gPopupContainer);
}

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function keyDownHandler(e)
{
    if (gPopupIsShown && e.keyCode == 9) 
    {
		 return false;
	}
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes(insideIFrame) 
{
	if (document.all) 
	{
		var i = 0;

		for (var j = 0; j < gTabbableTags.length; j++)
		{
			var tagElements = (insideIFrame) ? window.parent.document.getElementsByTagName(gTabbableTags[j]) : document.getElementsByTagName(gTabbableTags[j]);

			for (var k = 0 ; k < tagElements.length; k++) 
			{
				gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
function restoreTabIndexes()
{
	if (document.all) 
	{
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) 
		{
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) 
			{
				tagElements[k].tabIndex = gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
}

/**
* Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*
*/
function hideSelectBoxes() 
{
	for(var i = 0; i < document.forms.length; i++) 
	{
		for(var e = 0; e < document.forms[i].length; e++)
		{
			if(document.forms[i].elements[e].tagName == "SELECT") 
			{
				document.forms[i].elements[e].style.visibility="hidden";
			}
		}
	}
}

/**
* Makes all drop down form select boxes on the screen visible so they do not reappear after the dialog is closed.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*/
function displaySelectBoxes(insideIFrame) 
{
    var formHandle = (insideIFrame) ? window.parent.document.forms : document.forms;

	for(var i = 0; i < formHandle.length; i++)
	{
		for(var e = 0; e < formHandle[i].length; e++)
		{
			if(formHandle[i].elements[e].tagName == "SELECT")
			{
				formHandle[i].elements[e].style.visibility="visible";
			}
		}
	}
}
/**
* Attach a function to the load event of the page
*/
//addLoadEvent(overlayInit);

function overlayInit()
{
   Fload = true;
}

/**
* Added by fix problem with 9msn header
*/
function fixPosition()
{
    if (window.parent.document.getElementById('hd_navUL') != undefined)
    {
		if (navigator.appName.indexOf('Microsoft') != -1)
			return window.parent.document.getElementById('hd_navUL').offsetHeight;
		else
			return window.parent.document.getElementById('hd_navUL').offsetHeight + 20;
    } else
    {
		return 0;
    }
}

removeNode = function(n)
{
  fIE=(navigator.appName.indexOf('Microsoft') != -1);
  if (fIE)
        n.removeNode(true);
	else if (n.parentNode)
		return n.parentNode.removeChild(n);
};

// Overlay functions end

