// <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
//
// $Id: common.js 76 2008-08-15 16:55:55Z alexfkl $
//

/*
 * jQuery Light config
 *
 */
var lightBoxConfig = {
		overlayBgColor: '#f0faff',
		overlayOpacity: 0.8,
		imageLoading: '/images/share/lightbox/lightbox-ico-loading.gif',
		imageBtnPrev: '/images/share/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: '/images/share/lightbox/lightbox-btn-next.gif',
		imageBtnClose: '/images/share/lightbox/lightbox-btn-close.gif',
		imageBlank: '/images/spacer.gif',
		containerBorderSize: 10,		// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
		containerResizeSpeed: 300,	// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
		txtImage: 'image',					// (string) Specify text "Image"
		txtOf: 'of',								// (string) Specify text "of"
		keyToClose: 'c',						// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the ESCAPE key is used to.
		keyToPrev: 'p',							// (string) (p = previous) Letter to show the previous image
		keyToNext: 'n'							// (string) (n = next) Letter to show the next image.
}


function roundToNdp (num, decimals) {
	var ledecimals = Number('1e'+decimals);

	return Math.round(parseFloat(num) * ledecimals) / ledecimals;
}
	

function formatCurrency ( symbol, num ) {
	num = num.toString().replace(/\$|\,/g,'');

	if(isNaN(num))
		num = "0";

	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();

	if(cents<10)
		cents = "0" + cents;

	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
					num.substring(num.length-(4*i+3));

	return (((sign)?'':'-') + symbol + num + '.' + cents);
}


/* Function printf(format_string,arguments...)
 * Javascript emulation of the C printf function (modifiers and argument types 
 *    "p" and "n" are not supported due to language restrictions)
 *
 * Copyright 2003 K&L Productions. All rights reserved
 * http://www.klproductions.com 
 *
 * Terms of use: This function can be used free of charge IF this header is not
 *               modified and remains with the function code.
 * 
 * Legal: Use this code at your own risk. K&L Productions assumes NO resposibility
 *        for anything.
 ********************************************************************************/
function printf(fstring)
  { var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }    
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg); 
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg)); 
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg); 
      }
    converters['E'] = function(flags,width,precision,arg) 
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);        
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);        
      }  
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  }
/* Function printf() END */


function newProductIconEffect ( imgId, hover ) {
	if (hover) {
		$('#' + imgId).fadeTo('fast', 0.1);
	} else {
		$('#' + imgId).fadeTo('medium', 1);
	}
	
	return true;
}


var changeLanguage = function ( newLang, thisPageUrl, thisPageQueryString ) {
	if (thisPageUrl != null) {
		var url = thisPageUrl + '?lc=' + newLang;
		
		if (thisPageQueryString != '') {
			url += '&' + thisPageQueryString;
		}
		
		document.location.href = url;
	}
	
	return false;
}


/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
function echeck(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);

	if (str.indexOf(at)==-1){
		return false;
	}
	
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false;
	}
	
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}
	
	if (str.indexOf(at,(lat+1))!=-1){
		return false;
	}
	
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	}
	
	if (str.indexOf(dot,(lat+2))==-1){
		return false;
	}
	
	if (str.indexOf(" ")!=-1){
		return false;
	}
	
	return true;		
}


function newWindow ( mypage, myname, w, h, scroll, pos ) {
	if ( pos == "random" ) {
		LeftPosition = ( screen.width ) ? Math.floor ( Math.random ( ) * ( screen.width - w ) ) : 100 ;
		TopPosition = ( screen.height ) ? Math.floor ( Math.random ( ) * ( ( screen.height - h ) - 75 ) ) : 100;
	}

	if ( pos == "center" ) {
		LeftPosition = ( screen.width ) ? ( screen.width - w ) / 2 : 100;
		TopPosition = ( screen.height ) ? ( screen.height - h ) / 2 : 100;
	} else if ( ( pos != "center" && pos != "random" ) || pos == null ) {
		LeftPosition = 0;
		TopPosition = 20;
	}

	settings = 'width=' + w +',height=' + h +',top=' + TopPosition +',left=' + LeftPosition +',scrollbars=' + scroll +',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';

	win = window.open ( mypage, myname, settings );

	if ( parseInt ( navigator.appVersion ) >= 4 ) {
		win.window.focus ( );
	}
	
	return win;
}


/*
 * Dreamweaver CS3 utilities
 */
function MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
    if (!isIE || !isWin){  
      var flashVer = -1;
      if (plugins && plugins.length > 0){
        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
        if (desc == "") flashVer = -1;
        else{
          var descArr = desc.split(" ");
          var tempArrMajor = descArr[2].split(".");
          var verMajor = tempArrMajor[0];
          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
          flashVer =  parseFloat(verMajor + "." + verMinor);
        }
      }
      // WebTV has Flash Player 4 or lower -- too low for video
      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

      var verArr = reqVerStr.split(",");
      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
  
      if (flashVer < reqVer){
        if (confirm(msg))
          window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
      }
    }
  } 
}


function populateSelectOptions ( htmlSelectId, opts, selectIndex ) {
	$(htmlSelectId).empty();

	for (var i = 0; i < opts.length; i++) {
		var o = document.createElement('option');
		var t = document.createTextNode(opts[i] + '');
		o.setAttribute('value', opts[i]);
		//o.setAttribute('selected', (i == selectIndex));
		o.appendChild(t);
		
//		var newOpt = $(document.createElement('option')).attr({value: opts[i], selected: (i == selectIndex)}).text(opts[i] + '');
		$(htmlSelectId).append(o);
	}
	
	try {
		$(htmlSelectId).val(opts[selectIndex]);
	} catch(e) {}

	return true;
}


function validateField ( fieldId, roundDecimals ) {
	var tmpVal = $('#' + fieldId).val();

	if (isNaN(tmpVal)) {
		tmpVal = 0;
	}

	tmpVal = roundToNdp(tmpVal, roundDecimals);
	$('#' + fieldId).val(tmpVal);
	
	return tmpVal;
}


/*
 * Function to handle Product Search box.
 *
 */
$(document).ready(function() {

	$('#productSearch').focus(function() {
		if (this.value == $('#emptyValue').val()) {
			this.value = '';
		}
	}).blur(function() {
		if (this.value == '') {
			this.value = $('#emptyValue').val();
		}
	});
	
	$('#frmProductSearch').submit(function() {
		var isErr = false;
		
		if (($('#productSearch').val() == '') || ($('#productSearch').val() == $('#emptyValue').val())) {
			isErr = true;
			$('#productSearch').focus();
	
			alert(msgStr.productSearchFieldEmpty);
		}

		// Change to GET method.
		if (!isErr) {
			window.location.href = this.action + '?k=' + $('#productSearch').val();
		}
	
		return false;
	});
		
});
