// Mail Order Express:	shop.js
//
// 15/11/02	Line Xero	Corrected bug in ParseQS.
// 10/01/08 Line Xero   Moved all client settings to client.js. Please include client.js along with this file in all your pages

//expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365));

if(typeof(clientfileloaded) == "undefined")
{
    alert("Warning - client.js not present in " + document.location);
}

/*
if (!na(refer)) {
    if (refer.indexOf(domain) == -1) {
        SetCookie('REF',refer, null);
    }
}
*/

// Set the affiliate cookies.
var searchString = window.location.search.substring(1);
var nameValuePairs = searchString.split(/&/);
var nameValuePair;
var name;
var value;
 
for (var i = 0; i < nameValuePairs.length; i++)
{
    nameValuePair = nameValuePairs[i].split(/=/);
 
    name = nameValuePair[0];    
    value = nameValuePair[1];
  
    name = name.toLowerCase();  
       
    if ((name == "adnetwork")  || (name == "source"))
    {
        name = "affiliate";
        
        if (typeof(value) != "undefined")
        {
            value = value.toLowerCase();
   
           // set expiry date to 60 days from now.
           var expiryDate = new Date ();
           expiryDate.setTime(expiryDate.getTime() + (60 * 24 * 3600 * 1000));
           
           SetCookie(name, value, expiryDate);
        }     
    }
}

function PlaySound( s )
{
 var win=window.open('/playsound.html?sound%3D'+s, 
       'soundWindow',
       'toolbar=yes,width=400,height=200,directories=yes,status=yes,scrollbars=yes,resize=yes,menubar=yes');
 win.focus();
}

function GetSC( key )
{
 var l=GetCookie(oKey);
 if( !na(l) ) {
   var i=l.indexOf( '¬'+key+'¬' );
   if( i >=0 ) {
     i=i+key.length+2;
     var ii=l.indexOf('|',i)
     return l.substr(i, ii-i);
   }
 }
 return null;
}

function na(v) {
    return (''+v=='null' || ''+v==uf || v=='');
    }

function SetSC( key,val )
{
 var l=GetCookie(oKey);
 if( na(l) ) { 
   l='¬'+key+'¬'+val+'|';
 }else{
   var i=l.indexOf( '¬'+key+'¬' );
   if( i >=0 ) {
     var vi=i+key.length+2;
     var ii=l.indexOf('|',vi)
     l=l.substr(0,i)+'¬'+key+'¬'+val+l.substr(ii,2000);
   }else{
     l=l+'¬'+key+'¬'+val+'|';
   }
 }
 SetCookie(oKey,l);
}

function BuyItem(item, qty, evt)
{
    var target = getTarget(evt);
    if(disableImageButton(target))
    {
        //The -1 values are used because those parameters are no longer used by the BY function anyway
        BY(item, -1, qty, -1);
    }
}

function BY( item, cat, qty, wid )
{
 var sid = GetSID();

 if (isNaN(item)) {
     if (document.bform != null) {
         for (i=0; i < document.bform.all.length; i++) {
             if (document.bform.all(i).tagName == "INPUT") {
                 if (document.bform.all(i).name.substr(0,3) == "QTY") {
                     item=document.bform.all(i).name.substr(3);
                     qty=document.bform.all(i).value;
                 }
             }
         }
         if (isNaN(item)) {
             top.document.location = "/basket/basket.asp";
         } else {
             top.document.location = "/basket/setbasket.asp?Add=&" + item + "=" + qty + "&" + sid;
         }
     } else {
         top.document.location = "/basket/basket.asp";
     } 
 } else {
     if( isNaN(qty) || parseInt(qty) < 1 ) {
           qty=1;
     }
     top.document.location = "/basket/setbasket.asp?Add=&" + item + "=" + qty + "&" + sid;
 }
}

function BuyMany(str)
{
    var sid = GetSID();
    parent.location = "/basket/setbasket.asp?Add=&" + str + "&" + sid;
}

function EmailMe(item)
{
    sURL = '/shop2/emailme.html?ac=' + item;
    DisplayRightPane(sURL);
}

function TellAFriendProd(item)
{
    sURL = '/tell_a_friend/tell_a_friend_prod.asp?prd=' + item;
    DisplayRightPane(sURL);
}

function GoBack() { history.back(); }
function CloseWindow(){this.close();}
function RunningQuery(){}

function handpicked(){HandPicked();}

//This function is no longer needed as frames are not used
function DisplayRightPane( sUrl )
{
 document.location = sUrl;
 /*
 if(parent.frames['target']) {
   parent.frames['target'].location=sUrl;
 }else{
   if (parent.parent.frames['target']) {
       parent.parent.frames['target'].location=sUrl;
   } else {
       document.location = "/shop2/fhom.asp?url=" + sUrl;
   }
 }
 */
}

function GetWID()
{
    return GetCookie('wlid');
 /*
    var w=GetCookie( 'WID' );
 if( na(w) ) {
   var w=GetSID();
   var d=new Date();
   d.setTime(d.getTime() + (86400*365000));
   w='W'+w.substr(0,31);
   SetCookie( 'WID', w, d );
 }
 return w;
 */
}

function GetSID()
{
  var s=GetCookie( 'SID' );
  if( na(s) ) {
    var d = new Date();
    s = ''+d.getMonth()+''+d.getDate()+''+d.getHours()+''+d.getMinutes()+d.getSeconds();
    var r = parseInt(Math.random() * 10000); r = r+'';
    s = sSidP + s + r.substr(0,4);
    d.setTime(d.getTime() + (86400*21000));
    SetCookie( 'SID', s, d );
  }
  return s;
}

function Home()
{
 var p;
 if( OnWeb() ) {
   p='/';
 }else{
   p='/localindex.html';
 }
 top.location=p;
}
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (';', offset);
if (endstr == -1)
  endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
var arg = name + '=';
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
  var j = i + alen;
  if (document.cookie.substring(i, j) == arg)
    return getCookieVal (j);
  i = document.cookie.indexOf(' ', i) + 1;
  if (i == 0) break; 
}
return null;
}

function SetCookie (name, value)
{
    var expdate = new Date();
    expdate.setYear(expdate.getFullYear() + 1);
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : expdate;
    var path = (argc > 3) ? argv[3] : '/';
    document.cookie = name + '=' + escape(value) +
      ((expires == null) ? '' : ('; expires=' + expires.toGMTString())) +
      ((path == null) ? '' : ('; path=' + path)) +
      ((domain == null) ? '' : ('; domain=' + domain));
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);  
var cval = GetCookie (name);
document.cookie = name + '=' + cval + '; expires=' + exp.toGMTString();
}

function NextPage( sCrit, sNext )
{
    str = escape(sCrit+'/next='+sNext);
    SetCookie(lqkey,str);
    DisplayRightPane( MyFinderBase() + str );
}

function PrevPage( sCrit, sNext )
{
    str = escape(sCrit+'/next='+sNext);
    SetCookie(lqkey,str);
    DisplayRightPane( MyFinderBase() + str );
}

function PBCAT( cat )
{
BaseFind( 'IMG%3D1/PB%3D1/CATEGORY%3D'+cat );
}

function ExtendedFind( sStr )
{
BaseFind( escape('EXFIND='+sStr) );
}

function MA( age )
{
 BaseFind( escape('AGE='+age) );
}

function MD( item )
{
DisplayRightPane( MyFinderBase() +'/page%3Dmoredetail.html/detailitem%3D'+item );
}

function MoreDetail( item )
{
str = '/page%3Dmoredetail.html/moredetail%3D'+item;
DisplayRightPane( MyFinderBase() + str );
}

function HP( item )
{
DisplayRightPane( MyFinderBase() +'/page%3Dmoredetail.html/detailitem%3D'+item );
}

function MT( item )
{
 BaseFind( 'MTT%3D1/THIS%3D'+item );
}

function Buyit( item )
{
 return BY( item, '', 1 );
}

function getFilenameFromUrl(strUrl)
{
    var split = strUrl.split("/");
    if(split.length > 1)
    {
        return split[split.length - 1];
    }
    return "";
}

function addwish( item, qty, evt)
{
 var target = getTarget(evt);
 
 //if the button is not disabled
 if(disableImageButton(target))
 {
     //disable the button

     var r,s;

     if( isNaN(qty) || parseInt(qty) < 1 ) {
       qty=1;
     }

     r=MyWishBase()+'/page%3Dwishlist.html/buy%3D'+qty+'/item%3D'+item;
     DisplayRightPane(r);
  }
}

/*Gets the source filename of the specified image element, if it has 'disabled' appended to it, returns false,
  otherwise appends 'disabled', reconstructs the filename, adds it back to the image element and returns true
*/
function disableImageButton(elemImg)
{
    var split = elemImg.src.split("/");
    var filename = split[split.length - 1];
    var extIndex = filename.lastIndexOf(".");
    var ext = "";
    if(extIndex > -1)
    {
        ext = filename.substring(extIndex);
    }
    var filenameNoExt = filename.substring(0, extIndex);
    
    if(filenameNoExt.indexOf("disabled") == -1)
    {
        filenameNoExt += "disabled";
        filename = filenameNoExt + ext;
        split[split.length - 1] = filename;
        elemImg.src = split.join("/");
        return true;
    }
    return false;
}

function ViewWish() {
 var r=MyWishBase()+'/page%3Dwishlist.html';
 DisplayRightPane(r);
}

function CgiBase()
{
 return '/cgi';
}

function MyWishBase()
{
 var r;
 r='/cgi/mywish.pl?'+GetURLTok();
 return r;
}

function FindSet( str )
{
 var pb;

 if( str.substr(0,12) != 'query_string' ) {
   str='query_string%3D'+str;
 }
 BaseFind( str );
}

function ToySearchClick(sQ)
{
    var str, p='';
    document.form.query_string.value=sQ;
    str='query_string=' + sQ;
    if( ''+document.form.page != uf )
    {
        p=document.form.page.value;
    }
    else
    {
        p='results.html';
    }
    
    SetCookie(lqkey,str);
    var href = MyFinderBase() + escape("/" + str + "/page" + p);
    document.form.action = href;
    document.form.submit();
}

function ToySearchSubmit()
{
    var inp=document.getElementById("INPUT_STR").value;
    if( inp=='' ) {
      inp=prompt('Please type a keyword or toy name to look for!', 'toys' );
      if( na(inp) ){inp='ALL';}
    }
    ToySearchClick( inp );
}

function ToySearchTop()
{
    var str,p='';
    var inp=document.getElementById("INPUT_STR").value;

    if( inp=='' ) {
      inp=prompt('Please type a keyword or toy name to look for!', 'toys' );
      if( na(inp) ){inp='ALL';}
    }
    document.form.query_string.value=inp;
    str='query_string='+inp;
    if( ''+document.form.page != uf ) {p=document.form.page.value;} else {p='results.html';}
    SetCookie(lqkey,str);
    top.location = "/shop2/fhom.asp?url=" + MyFinderBase() + escape('/'+str+'/page='+p);
}

function ToySearch()
{
    var str,p='';
    var inp=document.getElementById("INPUT_STR").value;

    if( inp=='' ) {
      inp=prompt('Please type a keyword or toy name to look for!', 'toys' );
      if( na(inp) ){inp='ALL';}
    }
    strURL = 'query_string%3D' + inp;
    if (document.form.supplier) {
        strURL = strURL + '/supplier%3D' + document.form.supplier.value;
    }
    BaseFind(strURL);

    return false;
}

function BaseFind(str) {

    if( str.indexOf( '/page') < 0 ) {
       str=str+'/page%3Dresults.html';
    }

    SetCookie(lqkey,str);
    RunningQuery();

    str=MyFinderBase()+'/'+str;

    document.location = str;
    //DisplayRightPane( str );
}

function DealDet( str )
{
    SetCookie(lqkey,'dealdet%3D'+str);
    RunningQuery();

    str='/deals/deal.asp?idr='+str;
    DisplayRightPane( str );
}

function FindSetSup( qStr, sStr )
{
return BaseFind( 'query_string%3D'+qStr+'/supplier%3D'+sStr );
}

function FindSetCat( qStr, cStr )
{
return BaseFind( 'query_string%3D'+qStr+'/CATEGORY%3D'+cStr );
}

function FindSupSetCat( sStr, qStr, cStr )
{
return BaseFind( 'query_string%3D'+qStr+'/CATEGORY%3D'+cStr+'/supplier%3D'+sStr );
}

function FindSupCat( sStr, cStr )
{
return BaseFind( 'supplier%3D'+sStr+'/CATEGORY%3D'+cStr );
}

function FindSup( sStr )
{
return BaseFind( 'supplier%3D'+sStr );
}

function FindDeal( sStr )
{
return BaseFind( 'deal%3D'+sStr );
}

function HalfPrice( sStr )
{
return BaseFind( 'halfprice%3D1/');
}

function FindSpecials( sStr )
{
return BaseFind( 'special%3D1/supplier%3D'+sStr );
}

function FindSpecialsCat( sStr )
{
return BaseFind( 'special%3D1/CATEGORY%3D'+sStr );
}

function FindSpecialsExt( sStr )
{
return BaseFind( 'special%3D1/EXFIND%3D'+sStr );
}

function FindDealDet( sStr )
{
return DealDet( 'dealdet%3D'+sStr );
}

function FindProd( sStr )
{
return BaseFind( 'query_string%3DMOE'+sStr );
}

function FindCat( sStr )
{
return BaseFind( 'CATEGORY%3D'+sStr );
}

function FindNew( sNew, sStr )
{
return BaseFind( 'new%3D' + sNew + '/supplier%3D'+sStr );
}

function FindNewExt( sNew, sStr )
{
return BaseFind( 'new%3D' + sNew + '/EXFIND%3D'+sStr );
}

function FindAward( sAward, sStr )
{
return BaseFind( 'award%3D' + sAward + '/supplier%3D'+sStr );
}

function FindAwardExt( sAward, sStr )
{
return BaseFind( 'award%3D' + sAward + '/EXFIND%3D'+sStr );
}

function HandPicked()
{
 BaseFind( '/page%3Dhandpicked.html/HP%3D1' );
}

function OnWeb() {
var l=document.location.toString();
l=l.substr(0,10);
return 1;
/*return ( l == 'http://www' | l == 'https://ww' ); */
}

function OnSecureWeb() {
var l=document.location.toString()
return ( l.substr(0,8) == 'https://' )
}

function MyURLBase() {
 return '/shop2'
}

function MyFinderBase() {
 var r,l,bpc,a;
 l=document.location.toString()
 bpc=GetCookie( bpckey );
 if( na(bpc) ) {
   bpc=defbpc;
   SetCookie( bpckey,bpc );
   SetCookie( psortkey, null );
 }

 r = "http://" + top.location.hostname + "/cgi/pfind.pl?BPC%3D" + bpc + GetURLTok();

 if( ''+GetCookie(imgkey) != '1' ) {
  r=r+'/IMG%3D1';
 }

 if( ''+GetCookie(titleskey) != '1' ) {
  r=r+'/PB%3D1';
 }

 srt = GetCookie(psortkey);
 if( '' + srt != '0' ) {
  r=r+'/PSRT%3D' + srt;
 }

 a=GetCookie( arckey );
 if( !na(a) ) {
  r=r+'/ARC%3D'+a;
 }
 return r;
}

function GetURLTok()
{
 var x=GetCookie( tokey );

 if(na(x)){x=0};
 SetCookie( tokey, parseInt(x)+1 );
 return '/TOK%3D'+x;
}

function ResultsLoaded()
{
 var ck;

 ck=GetCookie( 'FT' );

 if( na(ck) ) {
   var u='/ftimerhelp.html';
   SetCookie( 'FT',( new Date () ) );
   window.open(u, 
               'displayWindow',
               'toolbar=yes,width=535,height=490,directories=no,status=yes,scrollbars=yes,resize=yes,menubar=no');
 }
}

function Requery()
{;
 var bits, one, i;
 var lq=GetCookie(lqkey);

 // Replace the age in the last query string if there is an age selection on the page.
 if (document.bform) {
     if (document.bform.AGE) {
         if (!na(lq)) {
             if (lq == "") {
                 lq = 'AGE=' + document.bform.AGE.value;
             } else {
                 if (lq.indexOf('AGE') >= 0) {
                     bits = lq.split('/');

                     lq = '';
                     for (i=0; i<bits.length; i++) {
                         one = bits[i].split('=');
                         if (one[0] == 'AGE') {
                             if (lq == '') {
                                 lq = lq + 'AGE=' + document.bform.AGE.value;
                             } else {
                                 lq = lq + '/AGE=' + document.bform.AGE.value;
                             }
                         } else {
                             if (lq == '') {
                                 lq = lq + bits[i];
                             } else {
                                 lq = lq + '/' + bits[i];
                             }
                         }
                     }
                     lq = "/" + lq
                 } else {
                     lq = lq + '/AGE=' + document.bform.AGE.value;
                 }
             }
         } else {
             lq = 'AGE=' + document.bform.AGE.value;
         }
     }
 }

 if( !na(lq) ) {
     if( lq.indexOf( 'dealdet') >= 0 ) {
         DealDet(lq.substr(10));
     } else {
         BaseFind( lq );
     }
 }else{
   parent.location='/index.asp';
 }   
}

function MakeNewSID()
{
SetCookie('SID',null);
}

// ---------- //
//  This function is no longer needed as the functionality has been moved to the server side i.e. to the pfind Mod_QS.
function ParseQS(s)
{
    return s;
}
function ClearNames()
{
 SetCookie('NAME',null);
}

function PlayMe(sndname)
{
    var myElement = document.getElementById("music");
    var innerText = "<embed src='/shop/sounds/"+sndname+"' autostart='true' autoplay='true' hidden>";   
    myElement.innerHTML = innerText;
}

function StopMe()
{
    var myElement = document.getElementById("music");
    var innerText = "<embed src='/shop/sounds/none.wav' autostart='true' autoplay='true' hidden>";   
    myElement.innerHTML = innerText;
}

function setInStock(instock) {
    if (instock.checked) {
        SetCookie("instock", "Y", null);
    } else {
        SetCookie("instock", null, null);
    }
}
function SetTitles()
{
    if (document.bform) {
        if (document.bform.TITLES) {
            if (document.bform.TITLES.checked) {
                SetCookie( titleskey, '1');
            } else {
                SetCookie( titleskey, null);
            }
        }
    }
}
function SetBpc()
{
    if (document.bform) {
        if (document.bform.BPC) {
            var bval = parseFloat(document.bform.BPC.value);
            if (isNaN(bval) || bval < 1 || bval > 100) {
                bval = 10;
            }
            SetCookie(bpckey, bval);
        }
    }
}
function PsortChange()
{
    var srt;

    if (document.bform) {
        if (document.bform.SORT) {
            if (document.bform.SORT.value == 'more') {
                srt = GetCookie(psortkey);
                if (srt != '') {
                    document.bform.SORT.value = srt;
                } else {
                    document.bform.SORT.value = '0';
                }
                top.location = "/shop2/advanced.asp";
            } else {
                if(document.bform.SORT.value != '0') {
                    SetCookie( psortkey, document.bform.SORT.value );
                } else {
                    SetCookie( psortkey, null );
                }
            }
        }
    }
}
    
//Displays the currency conversion dialog
function showCurrencyDialog()
{
    return showModalDialog("/cgi/currency.asp", "Currencies", 75, 75, 120, 300);
}


//Displays a browser window with no back buttons etc, opened at the specified url
//NOTE: IE doesn't like spaces or other non-alphanumeric characters in the window name
function showModalDialog(strUrl, strWindowName, iTop, iLeft, iHeight, iWidth)
{
    return window.open(strUrl,
                strWindowName,
                "top=" + iTop + ",left=" + iLeft + ",height=" + iHeight + ",width=" + iWidth + ",modal=yes,status=no,resizable=no,scrollbars=no,location=no,menubar=no,toolbar=no"
                );
}

function MyAccount()
{
    var href = "https://" + top.location.hostname + "/account/index.asp";
    top.location = href;
}

//Hides the specified element on the page
function hideElement(elem)
{
    elem.style.visibility = "hidden";
    elem.style.display = "none";
    elem.style.zIndex = 0;
}


//This is a work around for ie's getElementsByName bug
//It returns an array of dom elements with the specified tag name and name attribute
function getElementsWithName(strTagName, strName)
{
    var arrMatchingElems = new Array();
    var arrElems = document.getElementsByTagName(strTagName.toLowerCase());
    for(var i = 0;i < arrElems.length;i++)
    {
        if(arrElems[i].name == strName)
        {
            arrMatchingElems[arrMatchingElems.length] = arrElems[i];
        }
    }
    return arrMatchingElems;
}

//Returns the element that fired the specified event
function getTarget(evt)
{
    if(!evt) var evt = window.event;
    if(evt.target) return evt.target;
    else if(evt.srcElement) return evt.srcElement;
}