function url_decode(str) {
     return unescape(str.replace(/\+/g, " "));
}
Encoder = {

	// When encoding do we convert characters into html or numerical entities
	EncodeType : "entity",  // entity OR numerical

	isEmpty : function(val){
		if(val){
			return ((val===null) || val.length==0 || /^\s+$/.test(val));
		}else{
			return true;
		}
	},
	// Convert HTML entities into numerical entities
	HTML2Numerical : function(s){
		var arr1 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		var arr2 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		return this.swapArrayVals(s,arr1,arr2);
	},	

	// Convert Numerical entities into HTML entities
	NumericalToHTML : function(s){
		var arr1 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		var arr2 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		return this.swapArrayVals(s,arr1,arr2);
	},


	// Numerically encodes all unicode characters
	numEncode : function(s){
		
		if(this.isEmpty(s)) return "";

		var e = "";
		for (var i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (c < " " || c > "~")
			{
				c = "&#" + c.charCodeAt() + ";";
			}
			e += c;
		}
		return e;
	},
	
	// HTML Decode numerical and HTML entities back to original values
	htmlDecode : function(s){

		var c,m,d = s;
		
		if(this.isEmpty(d)) return "";

		// convert HTML entites back to numerical entites first
		d = this.HTML2Numerical(d);
		
		// look for numerical entities &#34;
		arr=d.match(/&#[0-9]{1,5};/g);
		
		// if no matches found in string then skip
		if(arr!=null){
			for(var x=0;x<arr.length;x++){
				m = arr[x];
				c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character
				// if its a valid number we can decode
				if(c >= -32768 && c <= 65535){
					// decode every single match within string
					d = d.replace(m, String.fromCharCode(c));
				}else{
					d = d.replace(m, ""); //invalid so replace with nada
				}
			}			
		}

		return d;
	},		

	// encode an input string into either numerical or HTML entities
	htmlEncode : function(s,dbl){
			
		if(this.isEmpty(s)) return "";

		// do we allow double encoding? E.g will &amp; be turned into &amp;amp;
		dbl = dbl | false; //default to prevent double encoding
		
		// if allowing double encoding we do ampersands first
		if(dbl){
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}
		}

		// convert the xss chars to numerical entities ' " < >
		s = this.XSSEncode(s,false);
		
		if(this.EncodeType=="numerical" || !dbl){
			// Now call function that will convert any HTML entities to numerical codes
			s = this.HTML2Numerical(s);
		}

		// Now encode all chars above 127 e.g unicode
		s = this.numEncode(s);

		// now we know anything that needs to be encoded has been converted to numerical entities we
		// can encode any ampersands & that are not part of encoded entities
		// to handle the fact that I need to do a negative check and handle multiple ampersands &&&
		// I am going to use a placeholder

		// if we don't want double encoded entities we ignore the & in existing entities
		if(!dbl){
			s = s.replace(/&#/g,"##AMPHASH##");
		
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}

			s = s.replace(/##AMPHASH##/g,"&#");
		}
		
		// replace any malformed entities
		s = s.replace(/&#\d*([^\d;]|$)/g, "$1");

		if(!dbl){
			// safety check to correct any double encoded &amp;
			s = this.correctEncoding(s);
		}

		// now do we need to convert our numerical encoded string into entities
		if(this.EncodeType=="entity"){
			s = this.NumericalToHTML(s);
		}

		return s;					
	},

	// Encodes the basic 4 characters used to malform HTML in XSS hacks
	XSSEncode : function(s,en){
		if(!this.isEmpty(s)){
			en = en || true;
			// do we convert to numerical or html entity?
			if(en){
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&quot;");
				s = s.replace(/</g,"&lt;");
				s = s.replace(/>/g,"&gt;");
			}else{
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&#34;");
				s = s.replace(/</g,"&#60;");
				s = s.replace(/>/g,"&#62;");
			}
			return s;
		}else{
			return "";
		}
	},

	// returns true if a string contains html or numerical encoded entities
	hasEncoded : function(s){
		if(/&#[0-9]{1,5};/g.test(s)){
			return true;
		}else if(/&[A-Z]{2,6};/gi.test(s)){
			return true;
		}else{
			return false;
		}
	},

	// will remove any unicode characters
	stripUnicode : function(s){
		return s.replace(/[^\x20-\x7E]/g,"");
		
	},

	// corrects any double encoded &amp; entities e.g &amp;amp;
	correctEncoding : function(s){
		return s.replace(/(&amp;)(amp;)+/,"$1");
	},


	// Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals
	swapArrayVals : function(s,arr1,arr2){
		if(this.isEmpty(s)) return "";
		var re;
		if(arr1 && arr2){
			//ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length)
			// array lengths must match
			if(arr1.length == arr2.length){
				for(var x=0,i=arr1.length;x<i;x++){
					re = new RegExp(arr1[x], 'g');
					s = s.replace(re,arr2[x]); //swap arr1 item with matching item from arr2	
				}
			}
		}
		return s;
	},

	inArray : function( item, arr ) {
		for ( var i = 0, x = arr.length; i < x; i++ ){
			if ( arr[i] === item ){
				return i;
			}
		}
		return -1;
	}

}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function awp_select(group,attribute, currency, first)
{
	//if (first)
		//alert("awp_select("+group+","+attribute+","+first);
	//alert(group + " - "+ attribute + " = "+awp_selected_groups.toString())
	var awp_curr_prices = awp_price_update();
	//alert(awp_curr_prices['priceProduct']);
	var curr_price = awp_curr_prices['priceProduct'];
	if (!first)
	{
		awp_select_image(attribute);
		if ($('#awp_add_to_cart input').val() != awp_add_cart)
		{
			$('#awp_add_to_cart input').val(awp_add_cart);
			$('#awp_add_to_cart input').unbind('click').click(function(){
				awp_add_to_cart();
				return false;
			});
		}
	}
	//alert(group+", "+attribute+", "+currency+", "+first);
	var name = document.awp_wizard;
	var default_impact = parseFloat($("#pi_default_"+group).val());
	var current_impact = parseFloat(awp_impact_list[attribute] != undefined?awp_impact_list[attribute]:0);
	//alert("1) " + awp_selected_groups[group]);
	awp_selected_groups[group] = attribute;
	$("#pi_default_"+group).val(current_impact);
	if (awp_pi_display != "")
	{
		for (var id_attribute in awp_impact_list)
		{
			var id_group = awp_attr_to_group[id_attribute];
			var group_type = awp_group_type[id_group];
			if (awp_selected_groups[id_group] == undefined || (awp_pi_display == "total" && parseFloat(awp_impact_list[id_attribute]) == 0))
				continue;
			var tmp_attr = (group_type != "checkbox" && awp_selected_groups[id_group] != 0?awp_selected_groups[id_group]:id_attribute);
			current_impact = parseFloat(awp_impact_list[tmp_attr]);
			if (id_group == -4)
				alert(awp_selected_groups[id_group]+" - "+id_attribute + " == " +tmp_attr);
			//alert(is_checkbox + " | " +id_group + " --->>> " + id_attribute + " = " + tmp_attr + " == " +current_impact);
			if ((awp_group_impact[id_group] == 1 && id_group == group && (awp_pi_display != "total" || first))
					||
				(awp_pi_display == "total" && !first))
			{
				var selected = document.getElementById("awp_group_"+id_group)?document.getElementById("awp_group_"+id_group).selectedIndex:0;
				var select_group = false;
				//if (!first)
					//alert(group +" - "+ id_attribute);
				var html = " ";
				if ($("#awp_group_per_row_"+id_group).val() > 1 && $("#awp_group_layout_"+id_group).val() == 1 && awp_hin[id_group] != 1)
					html = "<br />";
				if (awp_pi_display == "diff")
				{
					var itr_impact = awp_impact_list[id_attribute];
					//alert(current_impact + " = " + itr_impact + " ("+attribute+" = "+id_attribute+")");
					if (current_impact < itr_impact)
						html += "["+awp_add+" "+ formatCurrency((Math.round(Math.abs(current_impact - itr_impact)) == Math.abs(current_impact - itr_impact)?Math.abs(current_impact - itr_impact):Math.abs(current_impact - itr_impact)), currencyFormat, currencySign, currencyBlank)+"]";
					else if (current_impact > itr_impact)
						html += "["+awp_sub+" "+ formatCurrency((Math.round(Math.abs(itr_impact - current_impact)) == Math.abs(itr_impact - current_impact)?Math.abs(itr_impact - current_impact):Math.abs(itr_impact - current_impact)), currencyFormat, currencySign, currencyBlank)+"]";
					//alert(html);
				}
				else
				{
					var itr_impact = parseFloat(awp_impact_list[id_attribute]);
					var att_selected = false;
					if (awp_selected_groups[id_group] == id_attribute)
						att_selected = true;
					//if (!first)
					//	alert(id_group+" --------> "+id_attribute+") "+is_checkbox+ " --- "+current_impact +" - "+ itr_impact + " == " +att_selected);
					//if ((group_type == "checkbox" && !$("#awp_checkbox_group_"+id_attribute).attr('checked')) || (true))
					//{
					if (itr_impact != 0)
					{
						//alert("awp_get_total_prices ("+id_group+","+id_attribute+") - " + itr_impact);
						var tmp_arr = new Array();
						//if (current_impact < itr_impact)
						/*if (group_type == "checkbox" || group_type == "quantity")
							tmp_arr = awp_get_total_prices(group_type != "checkbox" || !$("#awp_checkbox_group_"+id_attribute).attr('checked')?itr_impact:0);
						else
							tmp_arr = awp_get_total_prices(itr_impact - current_impact);
							//tmp_arr = awp_get_total_prices(current_impact - itr_impact);
						var awp_new_price = tmp_arr['priceProduct'];*/
						if (id_group == 1114)
							alert(id_group+" - "+id_attribute+") "+curr_price + " - " +current_impact + " - " +itr_impact);
						var awp_new_price = curr_price;
						if (current_impact < itr_impact)
							awp_new_price += (itr_impact - current_impact);
						else if (current_impact > itr_impact)
							awp_new_price = awp_new_price - current_impact + itr_impact;
						html += "["+formatCurrency(awp_new_price * currencyRate, currencyFormat, currencySign, currencyBlank)+"]";
					}
					//alert(awp_new_price+ " = " +html);
						//if (is_checkbox)
						//	alert(id_group+" --------> "+id_attribute+")  "+current_impact +" - "+itr_impact +" = "+ awp_new_price + " == " +html);
					//}
				}
				if ($("#price_change_"+id_attribute).length != 0)
				{
					//if (!first)
						//alert(id_group+" -> "+id_attribute+") "+current_impact +" ("+$("#awp_radio_group_"+id_attribute).attr('checked')+") - "+ itr_impact + " == " +html);
					//alert(id_attribute+ " - " + html);
					$("#price_change_"+id_attribute).html(html);
					//alert($("#awp_cell_"+split[3]).width());
					//$("#awp_tc_"+split[3]).css('margin-left', ($("#awp_cell_"+split[3]).width() - $("#awp_tc_"+split[3]).width()) /2);
				}
				else if (document.getElementById("awp_group_"+id_group) && document.getElementById("awp_group_"+id_group).options)
				{
					var currentSB = document.getElementById("awp_group_"+id_group);
					var sb_index = 0;
					var tmp_index = 0;
					$("#awp_group_"+id_group+" option").each(function() {
						if (id_attribute == $(this).val())
							sb_index = tmp_index;
						tmp_index++;
					});
//					for (var tmp_index in currentSB.options)
//					{
//						alert(id_attribute + " == " + currentSB.options[tmp_index].value + " = " + sb_index + " - "+tmp_index)
//						if (id_attribute == currentSB.options[tmp_index].value)
//							sb_index = tmp_index;
//					}
					var current = document.getElementById("awp_group_"+id_group).options[sb_index].text;
					//if (!first)
					//	alert(id_group+" -> "+id_attribute+" ["+sb_index+"]>> "+current_impact +" - "+ itr_impact + " ("+current+") == " +html);
					//alert(id_attribute + " = " + sb_index + " = " + current + " | "+ html);
					if (current.indexOf("[") > 0)
						current = current.substring(0,current.indexOf("["));
					document.getElementById("awp_group_"+id_group).options[sb_index]=new Option(current+html, id_attribute)
					document.getElementById("awp_group_"+id_group).selectedIndex = selected;
					//alert("Select box " + split[4] + " -- " + current+html);
					select_group = true;
				}
			}
		}
	}
	//setTimeout(function() {$("#awp_tc_"+split[3]).css('margin', 'auto')},3000);
	//if (select_group && document.getElementById("awp_group_"+group))
		//adocument.getElementById("awp_group_"+group).selectedIndex = selected;
	//alert("2) " + awp_selected_groups[group]);
	if (document.getElementById('awp_price'))
		$("#awp_price").html($("#our_price_display").html())
	if (document.getElementById('awp_second_price'))
		$("#awp_second_price").html($("#our_price_display").html())
}

function awp_get_total_prices(awp_extra)
{
	var doa = false;
	awp_extra = parseFloat(awp_extra);
	var name = document.awp_wizard;
	var awp_total_impact = 0;
	var awp_total_weight = 0;
	var awp_total_impact_quantity = new Array();
	var awp_total_weight_quantity = new Array();
	var awp_total_quantity_quantity = new Array();
	var awp_quantity = 0;
	var awp_first = true;
	//alert ("start awp_get_total_prices");
	var loop = 0;
	$('#awp_box .awp_attribute_selected').each(function()
	{
		if (($(this).attr('type') != 'radio' || $(this).attr('checked')) &&
			($(this).attr('type') != 'checkbox' || $(this).attr('checked')) &&
			($(this).attr('type') != 'text' || $(this).val() != "0") &&
				$(this).val() != "")
		{
			var awp_arr = $(this).attr('name').split('_');
			var found = false;
			for (key in awp_impact_list)
				if (key == $(this).val())
					found = true;
			//alert($(this).attr('name') + " ("+awp_arr.length+" , "+found+") == " + $(this).val());
			if (found)
			{
				if (!awp_arr[2] || awp_group_type[awp_arr[2]] != "quantity") 
				{
					awp_total_impact += parseFloat(awp_impact_list[$(this).val()]);
					awp_total_weight += parseFloat(awp_weight_list[$(this).val()]);
				}
				/*else if(awp_group_type[awp_arr[2]] == "quantity")
				{
					awp_total_impact_quantity.push(awp_impact_list[awp_arr[3]]);
					awp_total_weight_quantity.push(awp_weight_list[awp_arr[2]]);
					awp_total_quantity_quantity.push($(this).val());
				}*/
		//	alert("qty"  + name.elements[i].value + " = " +parseInt($("#awp_qty_"+name.elements[i].value).val()) + " === "+awp_quantity);
				//			if (awp_quantity > parseInt($("#awp_qty_"+name.elements[i].value).val()))
				//				awp_quantity = parseInt($("#awp_qty_"+name.elements[i].value).val());
				if (awp_first || awp_quantity > parseInt(awp_qty_list[$(this).val()]))
					awp_quantity = parseInt(awp_qty_list[$(this).val()]);
				awp_first = false;
				awp_selected_groups[awp_arr[2]] = $(this).val();
			}
			else 
			{
				if ($(this).val() != "" && awp_arr.length == 4)
				{	
					if ((!awp_arr[2] || awp_group_type[awp_arr[2]] != "quantity")  && awp_impact_list[awp_arr[3]]) 
					{
						awp_total_impact += parseFloat(awp_impact_list[awp_arr[3]]);
						awp_total_weight += parseFloat(awp_weight_list[awp_arr[3]]);
					}
					/*else if(awp_group_type[awp_arr[2]] == "quantity")
					{
						awp_total_impact_quantity.push(awp_impact_list[awp_arr[3]]);
						awp_total_weight_quantity.push(awp_weight_list[awp_arr[3]]);
						awp_total_quantity_quantity.push($(this).val());
					}*/
					if (awp_first || awp_quantity > parseInt(awp_qty_list[awp_arr[3]]))
						awp_quantity = parseInt(awp_qty_list[awp_arr[3]]);
					awp_first = false;
					awp_selected_groups[awp_arr[2]] = awp_arr[3];
				}
			}
		}
	});
	/*
	var attribut_price_tmp_quantity = 0;
	for (var i = 0 ; i < awp_total_impact_quantity.length ; i++)
	{
		attribut_price_tmp_quantity += awp_total_impact_quantity[i] * awp_total_quantity_quantity[i];
		awp_total_weight += awp_total_weight_quantity[i] * awp_total_quantity_quantity[i];
	}
	awp_total_impact += attribut_price_tmp_quantity;
	*/
	var attribut_price_tmp = awp_total_impact;
	if (doa)
	alert("price 1 "+attribut_price_tmp);
	var tax = noTaxForThisProduct ? 1:((taxRate / 100) + 1);
	var attr_tax = noTaxForThisProduct ? ((taxRate / 100) + 1):1;
	if (noTaxForThisProduct)
	{
		attribut_price_tmp /= attr_tax;
		if (doa)
		alert("price 2 "+attribut_price_tmp +" attr_tax = "+attr_tax);
		//awp_total_impact /= attr_tax;
	}

	if (false && selectedCombination['reference'])
	{
		$('#product_reference span').text(selectedCombination['reference']);
		$('#product_reference:hidden').show();
	}
	else
		$('#product_reference').show();
		//$('#product_reference:visible').hide('slow');
	//alert("awp_extra "+awp_extra+" , attribut_price_tmp + "+ attribut_price_tmp + " + productPriceWithoutReduction " + productPriceWithoutReduction)
	var productPriceWithoutReduction2 = (awp_extra + attribut_price_tmp * currencyRate) + productPriceWithoutReduction;
	if (doa)
	alert("productPriceWithoutReduction2 = "+ productPriceWithoutReduction2 + " ("+attribut_price_tmp+" + "+productPriceWithoutReduction+" * "+currencyRate+")");
		
	if (reduction_from != reduction_to && (currentDate > reduction_to || currentDate < reduction_from))
		var priceReduct = 0;
	else
		var priceReduct = productPriceWithoutReduction2 / 100 * parseFloat(reduction_percent) + (reduction_price * currencyRate);
	var priceProduct = productPriceWithoutReduction2 - priceReduct;
	if (doa)
	alert("priceProduct = "+ priceProduct + " ("+productPriceWithoutReduction2+" - "+priceReduct+")");
	var productPricePretaxed = (productPriceWithoutReduction2 - priceReduct) / tax;

	if (typeof displayPrice != 'undefined' && displayPrice == 1)
	{
		priceProduct = productPricePretaxed;
		productPriceWithoutReduction2 /= tax;
	}
	if (typeof group_reduction != 'undefined' && group_reduction)
		priceProduct *= group_reduction;
	var arr = new Array();
	arr['priceProduct'] = priceProduct;
	arr['productPricePretaxed'] = productPricePretaxed;
	arr['productPriceWithoutReduction2'] = productPriceWithoutReduction2;
	arr['awp_quantity'] = awp_quantity;
	arr['awp_total_impact'] = awp_total_impact;
	arr['awp_total_weight'] = awp_total_weight;
	//alert(arr);
	return arr;
}

function awp_price_update()
{
	var prices = awp_get_total_prices(0);
	//alert(prices.toSource());
	var priceProduct = prices['priceProduct'];
	var productPricePretaxed = prices['productPricePretaxed'];
	var productPriceWithoutReduction2 = prices['productPriceWithoutReduction2'];
	var awp_quantity = prices['awp_quantity'];
	var awp_total_impact = prices['awp_total_impact'];
	var awp_total_weight = prices['awp_total_weight'];
	$('#our_price_display').text(formatCurrency(priceProduct, currencyFormat, currencySign, currencyBlank));
	$('#pretaxe_price_display').text(formatCurrency(productPricePretaxed, currencyFormat, currencySign, currencyBlank));
	$('#old_price_display').text(formatCurrency(productPriceWithoutReduction2, currencyFormat, currencySign, currencyBlank));
	if (awp_quantity == 0)
		$('#availability_value').html(availableLaterValue);
	else
		$('#availability_value').html(availableNowValue);
	
	$('#quantityAvailable').html(awp_quantity+" ");
	if (awp_quantity == 1)
	{
		$("#quantityAvailableTxt").css('display','');
		$("#quantityAvailableTxtMultiple").css('display','none');
	}
	else
	{
		$("#quantityAvailableTxtMultiple").css('display','');
		$("#quantityAvailableTxt").css('display','none');
	}
	$('#availability_statut').fadeIn('slow');
	if (awp_stock && awp_display_qty)
	{
		$('#quantityAvailable').fadeIn('slow');
		$('#awp_in_stock').html($('#availability_statut').html() + " " +$('#quantityAvailable').html() + (awp_quantity?$("#quantityAvailableTxt").html():$("#quantityAvailableTxtMultiple").html()));
		if (document.getElementById('awp_second_price'))
			$('#awp_in_stock_second').html($('#availability_statut').html() + " " +$('#quantityAvailable').html() + (awp_quantity?$("#quantityAvailableTxt").html():$("#quantityAvailableTxtMultiple").html()));
	}
	$('#awp_p_impact').val(awp_total_impact);
	$('#awp_p_weight').val(awp_total_weight);
	if (document.getElementById('awp_price'))
		$("#awp_price").html($("#our_price_display").html())
	if (document.getElementById('awp_second_price'))
		$("#awp_second_price").html($("#our_price_display").html())
	return prices;
}

function awp_add_to_cart()
{
	vars = awp_get_attributes();
	if (!vars)
		return false;
	vars["price"] = $('#awp_p_impact').val();
	vars["weight"] = $('#awp_p_weight').val();
	vars["quantity"] = $('#quantity_wanted').val();
	vars["quantity_available"] = $('#quantityAvailable').html();
	vars["id_product"] = $('#product_page_product_id').val();
	vars["awp_isie"] = ($.browser.msie?"1":"0");
	vars["allow_oos"] = allowBuyWhenOutOfStock?"1":"";
	//check for quantity
	if (vars["quantity_available"] == 0 && !allowBuyWhenOutOfStock)
	{
		alert(awp_oos_alert);
		return;
	}
	var quantity_group = "";
	//alert(awp_is_quantity_group.toSource());
	for (qty in awp_is_quantity_group)
		quantity_group = quantity_group + (quantity_group!=""?",":"")+awp_is_quantity_group[qty];
	vars["awp_is_quantity"] = quantity_group;
	//return;
	$('html, body').animate({ scrollTop: 0 }, "slow");
	//$.scrollTo( 0, 1200 );
	//return;
	$.ajax({
		type: 'POST',
		url: baseDir + 'modules/attributewizardpro/combination_json.php',
		async: false,
		cache: false,
		dataType : "json",
		data: vars,
		success:function(feed) { 
            // Do something with the response
			//alert(feed.toSource());
			//var cart_details = url_decode(feed.cart);
			var cart_details = (feed.cart);
			if (cart_details == "")
			{
				alert(awp_select_attributes);
				return;
			}
            if (awp_ajax)
			{
            	//cart_details = "1"+escape(cart_details);
				//apply 'transfert' effect
				var elementToTransfert = null;
				elementToTransfert = $('div#image-block');
				elementToTransfert.TransferTo({
							to: $('#cart_block').get(0),
							className:'transferProduct',
							duration: 800,
							complete: function () {
							}
				});
				
				$.ajax({
					type: 'GET',
					url: baseDir + 'cart.php',
					async: true,
					cache: false,
					dataType : "json",
					data: 'ajax=true&token=' + static_token,
					success: function(jsonData)
					{
						ajaxCart.updateCart(jsonData)
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						alert("TECHNICAL ERROR: unable to refresh the cart.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
					}
				});
            	//ajaxCart.refresh();
				//ajaxCart.add( $('#product_page_product_id').val(), feed.combination , true, null, (feed.qty?feed.qty:$('#quantity_wanted').val()), null, cart_details, feed.ids);
				awp_reset_text();
				awp_price_update();
				if (awp_popup)
				{
					$("#awp_container").fadeOut(1000);
					$("#awp_background").fadeOut(1000);
				}
				return;
	      	}
	      	else
	      	{
				location.href =  baseDir + 'order.php';
	      	}
		}
  	});
	return false;
}

function awp_customize_func()
{
	$('#awp_add_to_cart input').val(awp_customize);
	$('#awp_add_to_cart input').unbind('click').click(function(){
		$("#awp_background").fadeIn(1000);
		$("#awp_container").fadeIn(1000);
		$('#awp_add_to_cart input').val(awp_add_cart);
		$('#awp_add_to_cart input').unbind('click').click(function(){
			awp_add_to_cart();
			awp_customize_func();
			return false;
		});
	return false;
	});
}

function awp_add_to_cart_func()
{
	if ($('#awp_add_to_cart input').val() != awp_add_cart)
	{
		$('#awp_add_to_cart input').val(awp_add_cart);
		$('#awp_add_to_cart input').unbind('click').click(function(){
			awp_add_to_cart();
			return false;
		});
	}
}


function in_array(arr, obj)
{
	for(var i=0; i<arr.length; i++)
		if (arr[i] == obj)
			return true;
}

function awp_get_attributes()
{
	var name = document.awp_wizard;
	var vars = new Object();
	for(i=0; i<name.elements.length; i++)
		if (name.elements[i].name.substring(0,10) == "awp_group_" &&
			(name.elements[i].type != "radio" || name.elements[i].checked) &&
			(name.elements[i].type != "checkbox" || name.elements[i].checked) &&
			name.elements[i].name != "")
		{
			var tmp_arr = name.elements[i].name.substring(4).split("_");
			if (tmp_arr.length == 3)
			{
				var found = false;
				for (key in awp_required_list)
				{
					if (key == tmp_arr[2] && awp_required_list[key] == 1)
						found = true;
				}
				if (found && name.elements[i].value == "")
				{
					alert(Encoder.htmlDecode(awp_required_list_name[tmp_arr[2]])+" "+awp_is_required);
					name.elements[i].focus();
					return false;
				}
				else if (name.elements[i].value == "")
					continue;
				if (in_array(awp_is_quantity_group,tmp_arr[1]) && name.elements[i].value == 0)
					continue;
			}
			if (vars[name.elements[i].name.substring(4)])
				vars[encodeURI(name.elements[i].name.substring(4)+"_"+i)] = encodeURI(name.elements[i].value);
			else
				vars[encodeURI(name.elements[i].name.substring(4))] = encodeURI(name.elements[i].value);
		}
	return vars;
}

$(document).ready(function () {
	if ((awp_add_to_cart_display == "both" || awp_add_to_cart_display == "bottom") && document.getElementById('awp_price'))
	{
		$("#awp_price").html($("#our_price_display").html())
		$("#awp_second_price").html($("#our_price_display").html());
	}
	if ((BrowserDetect.browser != "Explorer" || BrowserDetect.version != "8") && (awp_add_to_cart_display == "both" || awp_add_to_cart_display == "scroll"))
	{
		$('#buy_block').css('position','relative');
		$('#buy_block').css('z-index','100');
    	$('#buy_block').scrollFollow( {
     	speed: 1000,
     	offset: 5,
     	container: 'awp_container'
    	});
    }
	for (var n = 0 ; n < awp_file_list.length ; n++)
	{
		var i = awp_file_list[n];
		new AjaxUpload('#upload_button_'+i, i, awp_file_ext[n], {
			action: baseDir + 'modules/attributewizardpro/file_upload.php',
			name: 'userfile',
			data: {	id_product :  $('#product_page_product_id').val(), id_attribute: i},
		  	// Submit file after selection
  			autoSubmit: true,
			responseType: false,
  			onSubmit: function(file, ext, i, allowed_ext)
  			{
				if (! (ext && allowed_ext.test(ext)))
				{
           			alert(awp_ext_err + " " + allowed_ext.source.substring(2,allowed_ext.source.length-2).replace(/\|/g,", "));
					return false;
		        }
        		$('#awp_image_cell_'+i).html('<img src="'+baseDir+'modules/attributewizardpro/img/loading.gif" /><br /><b>Please wait</b>');
  			},
  			onComplete: function(file, ext, response, i)
  			{
  				var response_arr = response.split("|||",2);
  				if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext)))
  					$('#awp_image_cell_'+i).html(response_arr[1]);
  				else
  				{
  					if (response.indexOf('|||') == -1)
  					{
  						alert(response);
  						$('#awp_image_cell_'+i).html('');
  	  					$('#awp_image_delete_cell_'+i).css('display','none');
  	  					$('#awp_file_group_'+i).val('');
  	  					awp_price_update();
  						return;
  					}
  					var thumb = response_arr[0].substr(0, response_arr[0].length - ext.length - 3)+"_small.jpg";
  					$('#awp_image_cell_'+i).html('<img src="'+baseDir+'modules/attributewizardpro/file_uploads/'+thumb+'" />');
  					$('#awp_image_cell_'+i).css('display','block');
  				}
        		$('#awp_image_delete_cell_'+i).css('display','block');
        		$('#awp_file_group_'+i).val(response);
        		awp_price_update();
  			}
		});
	}
	for (var id_attribute in awp_impact_list)
	{
		var tmp_impact = parseInt(awp_impact_list[id_attribute]);
		if (!awp_attr_to_group[id_attribute])
			continue;
		var tmp_group = awp_attr_to_group[id_attribute];
		if (tmp_impact != 0)
			awp_group_impact[tmp_group] = 1;
		else if(awp_group_impact[tmp_group] != 1)
			awp_group_impact[tmp_group] = 0;
	}
});

function awp_select_image(selected)
{
	var choice = new Array();
	//alert(selected.toSource());
	$('div#attributes select').each(function(){
		choice.push($(this).val());
	});
	var nbAttributesEquals = 0;
	//testing every combination to find the conbination's attributes' case of the user
	
	for (combination in combinations)
	{
		//verify if this combinaison is the same that the user's choice
		nbAttributesEquals = 0;
		for (idAttribute in combinations[combination]['idsAttributes'])
		{
			//ie6 bug fix
			if (idAttribute != 'indexOf'){
				//if this attribute has been choose by user
				if (combinations[combination]['idsAttributes'][idAttribute] ==  selected)
				{
					//we are in a good way to find the good combination !
					awpRefreshProductImages(combinations[combination]['idCombination']);
					displayImage( $('#thumb_'+combinations[combination]['image']).parent() );
					return;
				}
			}
		}
	}
}

function awpRefreshProductImages(id_product_attribute)
{
	if (typeof(refreshProductImages) != 'function')
		return;
	if (typeof(combinationImages) == 'undefined' || typeof(combinationImages[id_product_attribute]) == 'undefined')
		return;
	$('#thumbs_list_frame').scrollTo('li:eq(0)', 700, {axis:'x'});
	$('#thumbs_list li').hide();
	id_product_attribute = parseInt(id_product_attribute);
	var i = 0;
	if (typeof(combinationImages) != 'undefined' && typeof(combinationImages[id_product_attribute]) != 'undefined')
	{
		for (i = 0; i < combinationImages[id_product_attribute].length; i++)
			$('#thumbnail_' + parseInt(combinationImages[id_product_attribute][i])).show();
	}
	$('#thumbs_list_frame').width((parseInt(($('#thumbs_list_frame li').width())* i) + 3) + 'px'); //  Bug IE6, needs 3 pixels more ?
	$('#thumbs_list').trigger('goto', 0);
	if (typeof serialScrollFixLock == 'function')
		serialScrollFixLock('', '', '', '', 0);// SerialScroll Bug on goto 0 ?
}

function awp_reset_text()
{
	var name = document.awp_wizard;
	for(i=0; i<name.elements.length; i++)
		if (name.elements[i].name.substring(0,10) == "awp_group_" && 
			(name.elements[i].type == "text" || name.elements[i].type == "textarea" || name.elements[i].type == "hidden"))
			{
				if (name.elements[i].type == "hidden")
				{
					var img_arr = name.elements[i].value.split("_");
					$("#awp_image_cell_"+img_arr[1]).css('display','none');
					$("#awp_image_delete_cell_"+img_arr[1]).css('display','none');
					name.elements[i].value = "";
				}
				else
				{
					var group_arr = name.elements[i].name.split("_");
					if (awp_group_type[group_arr[2]] == "quantity")
						var foo = "bar";//name.elements[i].value = "0";
					else
						name.elements[i].value = "";
				}
			}
}
