var intervalid;
var basePath = ''
var intervalid2 = null;
var outstandingPayment = 0;

function getObj(id){
  if (document.getElementById){
    return document.getElementById(id);
  }
  else if (document.all){
    return document.all[id];
  }
  else if (document.layers){
    return getObjNN4(document,id);
  }
}

function getObjNN4(obj,id){
  var lyrs = obj.layers;
  var rtn;
  for (var i=0;i<lyrs.length;i++){
    if (lyrs[i].id == id){
      return lyrs[i];
    }else if(lyrs[i].document.layers.length){
      return getObjNN4(lyrs[i].document, id);
    }
  }
  return 0;
}

function ToggleDiv(id) {
    var o = getObj(id);
    if (o) {
        (o.style.display == "block") ? o.style.display = "none" : o.style.display = "block"
    }
}

function ToggleClass(obj, class1, class2) {
    if (obj.className == class1) {
        obj.className = class2;
    }
    else {
        obj.className = class1;
    }
}

function ToggleDiv2(id) {
    var o = getObj(id);
    (o.className.indexOf("hidden") > -1) ? o.className = o.className.replace("hidden", "display") : o.className = o.className.replace("display", "hidden");
}

/* Used only in account */
function AlternateBGColor(sID, iID , iCount) {
	var o = getObj(sID + iID);
	for(i=0;i<=iCount;i++) {
		if (getObj(sID + i) != null)
		{
			getObj(sID + i).className = "RowUnSelected";
		}
	}
	o.className = "RowSelected";
}

function SelectAll(sName,o) 
{
	if (o.checked) {
		var c = document.getElementsByName(sName);
		for(i=0;i<c.length;i++) {
			c[i].checked = "checked";
		}
	}
}

function ToggleImg(o) {
	if (o.src.indexOf("_on") == -1) {
		o.src = o.src.replace('.gif','_on.gif');
	} else {
		o.src = o.src.replace('_on','');
	}
}

function Tab(iTabID, iNumTabs, sPrefix, siteSection, text) {
    for (i = 0; i <= iNumTabs; i++) {
        if (getObj(sPrefix + 'Tab_' + i)) {
            getObj(sPrefix + 'Tab_' + i).className = "MiniTabUnSel";
            getObj(sPrefix + 'Content_' + i).style.display = "none";
        }
    }

	getObj(sPrefix + 'Tab_' + iTabID).className = "MiniTabSel";
	getObj(sPrefix + 'Content_' + iTabID).style.display = "block";

	//Get the boxtab element
	if (getObj(sPrefix + 'Tab_' + iTabID).parentNode.className == 'highlight') {
	    getObj(sPrefix + 'BoxTab').parentNode.className = 'highlight';
	}
	else {
	    if (getObj(sPrefix + 'BoxTab')) {
	        getObj(sPrefix + 'BoxTab').parentNode.className = '';
	    }
	}

    //Do we need to activate a carousel for the content?
	if (getObj('mycarousel-' + (iTabID + 1)) && sPrefix == 'tab') {
	    jQuery('#mycarousel-' + (iTabID + 1)).jcarousel({
	        scroll: 1,
	        size: 3
	    });
	}

	//track click
	if (siteSection != undefined && text != undefined) {
	    try {
	        pageTracker._trackPageview('/' + siteSection + '/tab-click/' + escape(text.replace(" ","")));
	    } catch (e) { }
	}
}

function CheckSrchFrm(f) {
	//If the user is not in a rental or shop section, search within the rental section (Default when an id of a section is passed through)
	javascript:document.forms['SrchFrm'].submit();
}

function doAction(f,o,v) {
	v != '' ? document.forms[f].elements[o].value = v : ""
	document.forms[f].submit();
}

function popInstructions(s) {
	window.open(basePath + "instructions.asp?ui=compact&id=" + s,"Win1","WIDTH=300,HEIGHT=400,scrollbars=1")
}

function popPrivacy() {
    window.open(basePath + "privacypolicy.asp", "Win1", "WIDTH=300,HEIGHT=400,scrollbars=1")
}

function popBuyPrePlayedInfo() {
    showDialog('preplayedDialog');
}

function popKeepItInfo() {
    showDialog('keepItDialog');
}

function popTradeInConditionInfo() {
    showDialog('tradeInDialog');
}

function popReturnsPolicy() {
    showDialog('returnsDialog');
}

var curPostItId = null;
var initPos = new Object();

function InitPos(left, top) {
    this.initLeft = left;
    this.initTop = top;
}

function popPostIt(id, caller, yOffset, alreadyVisible) {

    //Close the current one (if it's the same one, move it back so it acts as a toggle)
    if (curPostItId != null) {
        var ret = curPostItId == id;
        closePostIt(curPostItId);
        if (ret)
            return;
    }

    //Give default value for the yoffset
    if (yOffset == null)
        yOffset = 0;

    if (curPostItId != id || curPostItId == null) {
        curPostItId = id;

        if (alreadyVisible) {

            //Move to caller
            if (caller != null) {
                if (initPos[id] == null) {
                    initPos[id] = new InitPos(getObj(id).offsetLeft + 'px', getObj(id).offsetTop + 'px');
                }

                //IE moves from 0:0, which looks daft, so force values for left and top
                getObj(id).style.left = getObj(id).offsetLeft + 'px';
                getObj(id).style.top = getObj(id).offsetTop + 'px';

                //Move it
                jQuery('#' + id).animate({ top: (caller.offsetTop + yOffset) + 'px', left: (caller.offsetLeft + caller.offsetWidth) + 'px' });
                Show(id + '-close');
                getObj(id).style.zIndex = 11; //One more than drop down
            }
        }
        else {
            Show(id);
        }
    }

    //Tracking
    try {
        pageTracker._trackPageview('/trade-in-guide/postit-click/' + id);
    } catch (e) { }            
}

function closePostIt(id, hide) {

    if (hide) {
        HideIt(id);
    }
    else {
        if (initPos[id] != null) {
            jQuery('#' + id).animate({ top: initPos[id].initTop, left: initPos[id].initLeft });
        }

        HideIt(id + '-close');
        getObj(id).style.zIndex = 4;
    }

    curPostItId = null;
}

function popInfo(id,iWidth,iHeight) {

	//set default window size if params are not specified
	if (!iWidth)
	{
		iWidth=300;
	}
	if(!iHeight)
	{
		iHeight=400;
	}
	window.open(basePath + "info.asp?id=" + id, "Win1", "WIDTH=" + iWidth + ",HEIGHT=" + iHeight + ",scrollbars=1")
}

function Hide(n) {
    if (getObj(n)) {
        getObj(n).style.display = 'none';
    }
}

function HideIt(n) {
    if (getObj(n)) {
        getObj(n).style.display = 'none';
    }
}

function Show(n) {
    if (getObj(n)) {
        getObj(n).style.display = 'block';
    }
}

function CheckReason(o) {
	(o.options[o.selectedIndex].text == "Other...") ? Show('Other') : ""
}

function SubmitFrm(f) {
	getObj(f).submit();
}

function debug(v) {
    document.getElementById('debug').innerHTML += v + '<Br />'
}

/*  Ratings */
var gRatingUpdateCount = false;
function rate(a, updateCount) {

    var parentId = a.parentNode.parentNode.id;
    var data = parentId.split('_');

    var productid = data[1]
    var userid = data[2]
    var rating = a.className.substring(a.className.indexOf('-') + 1, a.className.length);

    //Do we want to update the ratings?
    gRatingUpdateCount = updateCount;

    if (rating.length == 1)
        rating += '.0';
    else
        rating = rating.substring(0, 1) + '.' + rating.substring(2, 1);

    var ratingId = 'prod_' + productid + '_' + userid;
    jQuery('#' + ratingId).fadeOut('slow');

    //Do rating
    SGSiteService.RateProduct(productid, userid, parseInt(rating), rate_return, OnError, OnError)

    //jQuery.post('default.asp', 'action=submit%20review&userid=' + userid + '&text=&productid=' + productid + '&Rating=' + rating + '&remote=1', rate_return);
}

function rate_return(retVal) {
    var data = retVal.split('_');
    if (parseInt(data[0]) == 0) {
        //Was successful
        //get the current rating field
        var curRating = getObj('prod_' + data[2] + '_' + data[3] + '_currating');
        var ratingId = 'prod_' + data[2] + '_' + data[3];

        var width = "";
        
        if (curRating) {
            switch (data[1].replace(".0",""))
            {
                case "0":
                    {
                        width = "0";
                        break;
                    }
                case "0.5":
                    {
                        width = "12";
                        break;
                    }
                case "1":
                    {
                        width = "20";
                        break;
                    }
                case "1.5":
                    {
                        width = "31";
                        break;
                    }
                case "2":
                    {
                        width = "40";
                        break;
                    }
                case "2.5":
                    {
                        width = "51";
                        break;
                    }
                case "3":
                    {
                        width = "60";
                        break;
                    }
                case "3.5":
                    {
                        width = "72";
                        break;
                    }
                case "4":
                    {
                        width = "80";
                        break;
                    }
                case "4.5":
                    {
                        width = "92";
                        break;
                    }
                case "5":
                    {
                        width = "100";
                        break;
                    }
            }

            var numRatingsIncrement = 1;

            //If the user has already rated this game, don't increment the counter
            if (document.getElementById(ratingId + '_currating').className.indexOf('current-rating-mem') > -1) {
                numRatingsIncrement = 0;
            }
            
            jQuery('#' + ratingId + '_currating').addClass('current-rating-mem').attr('style', 'width:' + width + '% !important;');
            jQuery('#' + ratingId).fadeIn('slow');

            //We don't want to show this information if we are in the playlist / view page as it's only showing our review
            if (gRatingUpdateCount)
            {
                if (getObj(ratingId + '_numratings')) {
                    //Get rating
                    var numRatings = parseInt(jQuery('#' + ratingId + '_numratings').text().replace(')', '').replace('(', ''));
                    jQuery('#' + ratingId + '_numratings').text('(' + (numRatings + numRatingsIncrement) + ')');
                    jQuery('#' + ratingId + '_numratings').stop().css("background-color", "#FFFF9C");
                }
                else {
                    jQuery('#' + ratingId).after('<span class="num-ratings" style="background-color: #FFFF9C">(1)</span>');
                }
            }
        }
        //location.reload() //Refresh the page
    }
}

function OnError() {
    alert('There was a problem carrying out that task! Please refresh the page and try again.');
}

function ShowAndPosition(id, link) {
    var menu = getObj(id);
    menu.style.left = ((getObj('homepageOptions').offsetLeft + getObj('homepageOptions').offsetWidth) - 633) + 'px';
    Show(id);
}

function submitSearch() {
    document.getElementById('SrchFrm').submit();
}

function cleanUrl(value) {
    return value.replace(' ', '-').toLowerCase();
}

//Fix to let firefox register click event
if (document.captureEvents) {
    HTMLElement.prototype.click = function() {
        var evt = this.ownerDocument.createEvent('MouseEvents');
        if (evt) {
            evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
            this.dispatchEvent(evt);
        }
    }
}

/* New Functions (Registration / Checkout )*/
function SGDateDropDownList_Validate(source, args) {
    var selects = source.parentNode.getElementsByTagName('select');
    if (selects.length == 2) //Is a card date
    {
        args.IsValid = selects[0].selectedIndex > 0 && selects[1].selectedIndex > 0;
    }
    else {
        args.IsValid = selects[0].selectedIndex > 0 && selects[1].selectedIndex > 0 && selects[2].selectedIndex > 0;
    }
}

//Checks without a blank entry
function SGDateDropDownList_Validate2(source, args) {
    var selects = source.parentNode.getElementsByTagName('select');
    args.IsValid = selects[0].selectedIndex > -1 && selects[1].selectedIndex > -1 && selects[2].selectedIndex > -1;
}

function toggleTariff(img, baseFileName, fee) {
    setTimeout('doToggle(\'' + img.id + '\',\'' + baseFileName + '\',' + fee + ')', 100);
}

function doToggle(imgid, baseFileName, fee) {
    var img = document.getElementById(imgid);
    resetTariffs(baseFileName);
    if (img.src.indexOf('-off') > -1) {
        img.src = baseFileName.replace('.', '-on.');
        if (img.parentNode.parentNode.parentNode.className.indexOf('-bestvalue') == -1)
            img.parentNode.parentNode.parentNode.className = 'tariff-sel';

        //Set total if exists
        if (getObj('sTotal')) {
            getObj('sTotal').innerHTML = '&pound;' + (outstandingPayment + fee);
        }
            
    } else {
        img.src = baseFileName.replace('.', '-off.');
    }    
}

function resetTariffs(baseFileName) {
    var imgs = document.getElementsByTagName('img');
    
    for(var i = 0 ; i < imgs.length ; i++)
    {
        if (imgs[i].src.replace('-off', '').replace('-on', '').indexOf(baseFileName) > -1) {
            imgs[i].src = baseFileName.replace('.', '-off.');

            if (imgs[i].parentNode.parentNode.parentNode.className.indexOf('-bestvalue') == -1)
                imgs[i].parentNode.parentNode.parentNode.className = 'tariff';
        }
    }
}

function setValue(input, value) {
    document.getElementById(input).value = value;
}

var curDialogId = null;

function showDialog(id) {
    //Set the height of the dialog to the height of the window
    document.getElementById('dialog-bg').style.height = getWindowHeight() + 'px';

    //Animate
    jQuery('#dialog-bg').css('filter','alpha(opacity=10)').show().animate({ 'opacity': 0.4 }, 300, null, function() { positionElement(id) });
    
    //Store for later
    curDialogId = id;

    //Hide alll selects
    jQuery('select').hide();
}

function hideDialog() {

    //Is the current dialog a video? If so, we want to remove it so it doesn't continue in background
    if (getObj('dialog-container')) {
        if (getObj('dialog-container').src.toLowerCase().indexOf('video.aspx?') > -1) {
            getObj('dialog-container').src = 'Video.aspx';
        }
    }

    //Hide the main box we are showing
    HideIt(curDialogId);
    
    //Dissolve the bg
    jQuery('#dialog-bg').animate({ opacity: 0.1 }, 300, null, function() { jQuery('#dialog-bg').hide() });
    
    //Reset
    curDialogId = null;

    //show all selects
    jQuery('select').show();
}

function positionElement(id) {
    var obj = document.getElementById(id);
    if (obj) {
        Show(id);  
        obj.style.left = (((getWindowWidth() / 2) - (obj.offsetWidth / 2))) + 'px';  
        obj.style.top = (((getWindowHeight() / 2) - (obj.offsetHeight / 2))) + 'px';
        if (parseInt(obj.style.top) < 0)
            obj.style.top = '0px';        
    }

}

function getWindowWidth() {
    if (document.innerWidth) {
        return document.innerWidth;
    }
    else if (document.documentElement.clientWidth) { 
        return document.documentElement.clientWidth;
    }
}

function getWindowHeight() {
    if (document.innerHeight) {
        return document.innerHeight;
    }
    else if (document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
}

function getScrollX() {
    if (window.pageXOffset)
    {
        return window.pageXOffset;
    }
    else if (document.documentElement && document.documentElement.scrollLeft)
    {
        return document.documentElement.scrollLeft;
    }
    else if (document.body)
    {
        return document.body.scrollLeft;
    }
}

function getScrollY() {
    if (window.pageYOffset) {
        return window.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        return document.documentElement.scrollTop;
    }
    else if (document.body) {
        return document.body.scrollTop;
    }
}

var CurToolTip = null;
var CurHelpItemIndex = null;

function showToolTip(id) {
    CurToolTip = id;
    ShowWithPositionCheck(id);
}

function ShowWithPositionCheck(id) {
    //First show
    Show(id);
    
    //Now work out whether we need to move it
    var offsetLeft = getObj(id).offsetLeft;
    var offsetWidth = getObj(id).offsetWidth;

    var windowRight = getWindowWidth();

    if ((offsetLeft + offsetWidth) > windowRight) {;
        getObj(id).style.right = '0px';
    }
}

function clearToolTip() {
    HideIt(CurToolTip);
    CurToolTip = null;
}

function showHIWHelp(obj, index) {
    CurHelpItemIndex = index;
    Show('hiw-' + CurHelpItemIndex + '-dialog');
    document.getElementById('hiw-' + index).className += '-hover-' + index;
}

function clearHIWHelp(obj, index) {
    obj.className = 'hiw-item';
    HideIt('hiw-' + CurHelpItemIndex + '-dialog');
    CurHelpItem = null
}

function disable(link) {
    if (link.tagName == 'INPUT') {
        if (link.type == 'image') {
            if (link.src.indexOf('disabled') == -1) {
                link.src = link.src.replace('.gif', '-disabled.gif');
                return true;
            }
            else {
                return false;
            }
        }
    }
    else {
        if (link.className.indexOf('disabled') == -1) {
            link.className = 'new-button-disabled';
            return true;
        }
        else {
            return false; //Has already been disabled so don't allow further interaction
        }
    }
}

function hover(obj) {
    if (obj.className.indexOf(' hover') > -1) {
        obj.className = obj.className.replace(' hover', '');
    }
    else {
        obj.className += ' hover';
    }
}

/* Drop Down */
var gDropDowns = [];
var gCurDropDown = null;

function DD(id) {
    gDropDowns[gDropDowns.length] = id;
}

function shDD(id) {
    doDropDown(id);
}

function doDropDown(id) {
    var ddid = id.replace('-l', '');

    //Hide account menu
    hideAccountMenu(true);

    //If we've found everything
    if (getObj(id) && getObj(ddid)) {
        var ddlink = document.getElementById(id);
        var dropdown = document.getElementById(ddid);

        //Clear any existing timeouts
        clearTimeout(intervalid);

        if (ddid != gCurDropDown) {
            hideDropDowns();
        }

        //Hide alll selects
        jQuery('select').hide();
        Show(ddid);
        dropdown.style.left = (ddlink.offsetLeft + (ddlink.offsetWidth / 2)) - (dropdown.offsetWidth / 2) + 'px';
        dropdown.style.top = (ddlink.parentNode.offsetTop + ddlink.parentNode.offsetHeight) + 'px';
        gCurDropDown = ddid;
    }
}

function clDD(id) {
    clearTimeout(intervalid);
    var ddid = id.replace('-l', '');
//    debug('Clearing drop down');
    intervalid = setTimeout('HideIt(\'' + ddid + '\');jQuery(\'select\').show();',1000);
}

function hideDropDowns() {
    for (var i = 0; i < gDropDowns.length; i++) {
        HideIt(gDropDowns[i]);
    }
}

function showVideo(id) {
    showDialog('sg-dialog');
    document.getElementById('dialog-container').src = basePath + 'Video.aspx?id=' + id;
    document.getElementById('dialog-container').className = 'video-container';
    document.getElementById('sg-dialog').className = 'dialog video-dialog';
}

function hideVideo(code) {
    document.getElementById('dialog-container').src = basePath + 'Video.aspx';
    hideDialog('sg-dialog');
}

function showUpload() {
    showDialog('sg-dialog');
    document.getElementById('dialog-container').src = basePath + 'ProfileDialog.aspx?action=avatar';
    document.getElementById('dialog-container').className = 'upload-container';
    document.getElementById('sg-dialog').className = 'dialog upload-dialog';    
}

function hideUpload() {
    document.getElementById('upload-container').src = basePath + 'ProfileDialog.aspx';
    hideDialog('sg-dialog');
}

function showChangeAlias() {
    showDialog('sg-dialog');
    document.getElementById('dialog-container').src = basePath + 'ProfileDialog.aspx?action=alias';
    document.getElementById('dialog-container').className = 'alias-container';
    document.getElementById('sg-dialog').className = 'dialog alias-dialog';
}

function hideChangeAlias() {
    document.getElementById('upload-container').src = basePath + 'ProfileDialog.aspx';
    hideDialog('sg-dialog');
}

function setAlias(alias) {
    document.getElementById('profile-alias').innerHTML = alias;
}

function setProfileImg(id) {
    var d = new Date();
    var rand = d.getFullYear() + "|" + d.getMonth() + "|" + d.getDate() + "|" + d.getHours() + "|" + d.getMinutes() + "|" + d.getSeconds() + "|" + d.getMilliseconds();
    document.getElementById('profile-img').src = 'DisplayImage.ashx?a=3&u=' + id + '&width=100&rand=' + rand;
}

function addListener(o, e, f) {
    if (o.addEventListener) {
        o.addEventListener(e, f, false);
    } else {
        o.attachEvent("on" + e, f)
    }
}

addListener(document, 'click', clickEvent);

function clickEvent(e) {
    var obj = (e.srcElement) ? e.srcElement : e.target;
    var id = (e.srcElement) ? e.srcElement.id : e.target.id;
    if (id == 'dialog-bg') {
        hideDialog();
    }

    if (document.getElementById('account_hovermenu')) {
        if (document.getElementById('account_hovermenu').style.display == 'block' && id.indexOf('account_hovermenu') == -1) {
            HideIt('account_hovermenu');
        }
    }

    if (gCurDropDown != null) {
        if (obj.className.indexOf('ddmenu') == -1) {
            HideIt(gCurDropDown);
            jQuery('select').show();
        }
    }
/*
    if (document.getElementById('tradein-container')) {
        if (document.getElementById('tradein-container').style.display == 'block'
        && id.indexOf('tradein-container') == -1
        && obj.parentNode.id.indexOf('tradein-container') == -1
        && obj.parentNode.parentNode.id.indexOf('tradein-container') == -1
        && obj.parentNode.parentNode.parentNode.id.indexOf('tradein-container') == -1
        && obj.parentNode.parentNode.parentNode.parentNode.id.indexOf('tradein-container') == -1
        && obj.parentNode.parentNode.parentNode.parentNode.parentNode.id.indexOf('tradein-container') == -1
    ) {
            HideIt('tradein-container');
        }
    }
*/

    if (document.getElementById('buy-container')) {
        if (document.getElementById('buy-container').style.display == 'block' && !objOrParentIsId(obj, 'buy-container')
    ) {
            HideIt('buy-container');
        }
    }

    if (document.getElementById('tradein-container')) {
        if (document.getElementById('tradein-container').style.display == 'block' && !objOrParentIsId(obj, 'tradein-container')
    ) {
            HideIt('tradein-container');
        }
    }    
}

function objOrParentIsId(obj, id) {
    while (obj != undefined) {
        if ((obj.id || '').indexOf(id) > -1) {
            return true;
        }
        else {
            obj = obj.parentNode;
        }
    }

    return false;
}

function checkPromoBox(txtCode, ltl) {
    if (txtCode.value.length > 0) {
        document.getElementById('promoMsg').innerHTML = 'Please click the \'Validate Code\' button';
    }
    else {
        document.getElementById('promoMsg').innerHTML = '';
    }

}

function toggleLM(id) {
    HideIt('btn1over');
    HideIt('description1')
    HideIt('btn2over');
    HideIt('description2')
    HideIt('btn3over');
    HideIt('description3')
    HideIt('btn4over');
    HideIt('description4')
    HideIt('btn5over');
    HideIt('description5')

    Show('btn' + id + 'over');
    Show('description' + id);

    //Tracking
    try {
        pageTracker._trackPageview('/learn-more/main-hover/' + id);
    } catch (e) { }    
}

var curTestamonial = 0;
var maxTestamonial = 10;
function nextTestamonial() {
    if (curTestamonial == maxTestamonial) {
        curTestamonial = 0;
    }
    
    curTestamonial++;

    for (var i = 1; i <= maxTestamonial; i++) {
        HideIt('testamonial' + i);
        HideIt('attribution' + i);
    }
    
    jQuery('#testamonial' + curTestamonial).fadeIn('slow');
    jQuery('#attribution' + curTestamonial).fadeIn('slow');

    //Tracking
    try {
        pageTracker._trackPageview('/learn-more/testimonial-click/' + curTestamonial);
    } catch (e) { }       
}

function toggleBasketSummary(close) {
    clearTimeout(intervalid);
    jQuery('#bc').toggle('slow', toggleBasketHeaderArrow());

    if (close)
        intervalid = setTimeout('toggleBasketSummary(false)', 4000);

    //Tracking
    try {
        pageTracker._trackPageview('/header-basket/toggle/');
    } catch (e) { }            
    
}

function toggleBasketHeaderArrow() {
    var bha = getObj('basket-header-arrow');
    if (bha.src.indexOf('-up') > -1) {
        bha.src = 'images/themes/sg/basket-down.gif';
    }
    else {
        bha.src = 'images/themes/sg/basket-up.gif';
    }
}

function getFlashObject(movieName) {
    if (window.document[movieName]) {
        return window.document[movieName];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[movieName])
            return document.embeds[movieName];
    } else {
        return document.getElementById(movieName);
    }
}

function playVideo(id) {
    var obj = getFlashObject(id);

    if (obj) {
        obj.SetVariable("player:jsPlay", 0);
    }
}

var numFaqCats = 8;

function showFaqCat(id, a) {
    for (var i = 1; i <= numFaqCats; i++) {
        HideIt('cat-' + i);
        setClass('title-cat-' + i, '');
    }

    Show(id);
    setClass(a, 'selected');

    //Tracking
    try {
        pageTracker._trackPageview('/trade-in-guide/faq-cat-click/' + id);
    } catch (e) { }        
}

function setClass(obj, cls) {

    if (typeof obj == "string") {
        obj = getObj(obj)
    }

    if (obj) {
        obj.className = cls;
    }
}

function showFaq(a, id) {
    ToggleDiv(id);

    if (elementDisplayBlock(id)) {
        setClass(a, 'selected');
    }
    else {
        setClass(a, '');
    }

    //Tracking
    try {
        pageTracker._trackPageview('/trade-in-guide/faq-click/' + id);
    } catch (e) { }            
}

function elementDisplayBlock(id) {
    if (getObj(id)) {
        return getObj(id).style.display == 'block';
    }
}

function doEmptyValueCheck_TradeIn() {
    var f = getObj('fSearchTradeIns');
    var tb = getFormElement(f, 'k');
    var hidden = getFormElement(f, 'f');

    if (tb.value.length == 0) {
        hidden.value = '37';
    }

    return true;
}

function getFormElement(f, id) {
    for (var i = 0; i < f.elements.length; i++) {
        if (f.elements[i].id == id)
            return f.elements[i];
    }

    return null;
}

function showAccountMenu() {
    clearTimeout(intervalid2); 
    hideDropDowns();
    ShowAndPosition('account_hovermenu', this)
}

function hideAccountMenu(closeNow) {
    var timeout = 1000;
    
    if (closeNow) {
        timeout = 0;
    }
    
    intervalid2 = setTimeout('HideIt(\'account_hovermenu\')', timeout)
}

function setErr(o) {
    o.className = 'img-error'; 
    o.src = 'images/blank.gif';
    o.style.height = '60px';
}

function ToggleReviewText(o, prId) {

    var summary = getObj('review_' + prId + '_summary');
    var complete = getObj('review_' + prId + '_complete');

    if (o.innerHTML.indexOf('More') > -1) {
        o.innerHTML = '&laquo; Less';
        summary.className = 'hidden';
        complete.className = 'inline';        
    }
    else {
        o.innerHTML = 'More &raquo;';
        summary.className = 'inline';
        complete.className = 'hidden';        
    }
}

function checkGiftTariffErr(id) {
    return parseInt(document.getElementById(id).value) > 0;
}

var Adverts = [];
var adIndex = null;
function Advert(src, url, title) {
    this.ImageSrc = src;
    this.Url = url;
    this.Title = title;
    Adverts[Adverts.length] = this;
}

function scrollAds(imgId, aId) {
    if (adIndex == null) {
        adIndex = 0;
    }
    else {
        adIndex++;
       
        if (adIndex >= Adverts.length)
            adIndex = 0;

        jQuery('#' + imgId).fadeOut('slow', function() {

            var img = getObj(imgId);
            img.src = Adverts[adIndex].ImageSrc;
            img.alt = Adverts[adIndex].Title;

            var a = getObj(aId);
            a.href = Adverts[adIndex].Url;

            jQuery('#' + imgId).fadeIn('slow');
        
         });

    }
    
    //Remove all instances of sel
    jQuery('.sel').removeClass('sel');
    jQuery('#ad-' + adIndex).addClass('sel');    
    
    intervalId = setTimeout('scrollAds(\'' + imgId + '\',\'' + aId + '\')', 7000);
}

function setAd(imgId, aId, index) {
    clearTimeout(intervalId);
    adIndex = index - 1;
    scrollAds(imgId, aId);
}

function updateWithdrawalTotal(obj) {
    var adminFee = parseFloat(document.getElementById('adminFee').innerHTML);
    var amount = parseFloat(obj.value);
    var total = adminFee + amount;
    if (total.toString() != 'NaN') {
        document.getElementById('newTotal').innerHTML = total.toFixed(2);
    }
}

function setCookie(key, value) {
    var now = new Date();
    now.setTime(now.getTime());
    var expires = new Date(now.getTime() + (1000 * 20));
    document.cookie = name + "=" + escape(value) + ";expires=" + expires.toGMTString() + ";path=/";
}

function getCookie(key) {
	var cookies = document.cookie.split( ';' );
	var cookie = '';
	var found = false;

	for ( i = 0; i < cookies.length; i++ )
	{
		cookie = cookies[i].split( '=' );
		var name = cookie[0].replace(/^\s+|\s+$/g, '');
		if (name == key)
		{
			found = true;
			if ( cookie.length > 1 )
			{
				return unescape( cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			break;
		}
		cookie = null;
    }
	
	if ( !found )
	{
		return null;
	}
}

function addToBasket(productId, channelId, quantity)
{
    //Get basketid from cookie
    var basketId = getCookie('BasketID');
    if (basketId == null) basketId = 0;
    SGSiteService.AddToBasket(basketId, productId, channelId, quantity, basket_Result, basket_Error, basket_Error);
}

function removeFromBasket(productId, channelId, quantity) {
    //Get basketid from cookie
    var basketId = getCookie('BasketID');
    if (basketId == null) basketId = 0;
    if (basketId > 0) {
        SGSiteService.RemoveFromBasket(basketId, productId, channelId, quantity, basket_Result, basket_Error, basket_Error)
    }
}

function basket_Result(obj)
{
    var basketId = parseInt(obj);

    if (obj > 0) {
        setCookie('BasketID', basketId);
    }
}

function basket_Error()
{
    //Do nothing for now
}

function submitRegForm(index) {
    var action = document.getElementById('aspnetForm').action;

    var qs = action.split('?')[1].split('&');
    var url = action.split('?')[0]
    var newQs = [];
    
    for (var i = 0; i < qs.length; i++) {
        if (qs[i].indexOf('=') > -1) {
            var keyValue = qs[i].split('=');

            if (keyValue[0] == "st") {
                newQs[newQs.length] = "st=" + index.toString();
            }
            else {
                newQs[newQs.length] = qs[i];
            }
        }
    }
    
    document.getElementById('aspnetForm').action = url + '?' + newQs.join('&');
}