/* 
	Apresvelo Base Object
	LM: 03-17-11

*/
jQuery(function ($) {
	$.root = $(document);	
	var uri = window.location.href,
		t = function (_s) { return $.trim(_s); },
		byId = function (_id) {return document.getElementById(_id);};
	// Geo Resources
	// http://onlinebusinesswiki.com/index.php/ECommerce#How_to_deal_with_a_global_audience_-_multi-currency_and_multi-lingual_sites	
	var CONFIG = {
		COUNTRY_COOKIE : 'apresvelo_country',
		COOKIE_OPTIONS : { expires: 100, path: '/', domain: 'apresvelo.com'}, // will expire after a hundread days...
		COOKIE_OPTIONS_REMOVE : { expires: -1, path: '/', domain: 'apresvelo.com'},
		COUNTRY : {
			US : 'us',
			AU : 'au',
			EU : 'eu',
			UK : 'uk'
		},
		DOMAIN : {
			US : 'http://us.apresvelo.com',
			AU : 'http://www.apresvelo.com',
			EU : 'http://eu.apresvelo.com',
			UK : 'http://uk.apresvelo.com'
		}		
	};
	
	// countries by region //
	var COUNTRY = {
		US : "AFGHANISTAN|ALGERIA|AMERICAN SAMOA|ANGOLA|ANTIGUA AND BARBUDA|ARGENTINA|ARUBA|AZERBAIJAN|BAHAMAS|BAHRAIN|BANGLADESH|BARBADOS|BELIZE|BENIN|BERMUDA|BHUTAN|BOLIVIA|BOTSWANA|BRAZIL|BRITISH INDIAN OCEAN TERRITORY|BRUNEI DARUSSALAM|BURKINA FASO|BURUNDI|CAMBODIA|CAMEROON|CANADA|CAPE VERDE|COTE d'IVOIRE|CENTRAL AFRICAN REPUBLIC|CHAD|CHILE|CHINA|CHRISTMAS ISLAND|COCOS (KEELING) ISLANDS|COLOMBIA|COMOROS|CONGO|CONGO, THE DEMOCRATIC REPUBLIC OF THE|COOK ISLANDS|COSTA RICA|CUBA|DJIBOUTI|DOMINICA|DOMINICAN REPUBLIC|ECUADOR|EGYPT|EL SALVADOR|EQUATORIAL GUINEA|ERITREA|ETHIOPIA|GABON|GAMBIA|GHANA|GREENLAND|GRENADA|GUAM|GUATEMALA|GUINEA|GUINEA-BISSAU|GUYANA|HAITI|HONDURAS|HONG KONG|INDIA|INDONESIA|IRAN, ISLAMIC REPUBLIC OF|IRAQ|ISRAEL|JAMAICA|JAPAN|JORDAN|KAZAKHSTAN|KENYA|KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF|KOREA, REPUBLIC OF|KUWAIT|KYRGYZSTAN|LAO PEOPLE'S DEMOCRATIC REPUBLIC|LEBANON|LESOTHO|LIBERIA|LIBYAN ARAB JAMAHIRIYA|MACAO|MADAGASCAR|MALAWI|MALAYSIA|MALDIVES|MALI|MARTINIQUE|MAURITANIA|MAURITIUS|MAYOTTE|MEXICO|MONGOLIA|MONTSERRAT|MOROCCO|MOZAMBIQUE|MYANMAR|NAMIBIA|NEPAL|NEW CALEDONIA|NICARAGUA|NIGER|NIGERIA|NIUE|NORFOLK ISLAND|NORTHERN MARIANA ISLANDS|OMAN|PAKISTAN|PALESTINIAN TERRITORY, OCCUPIED|PANAMA|PARAGUAY|PERU|PHILIPPINES|PITCAIRN|PUERTO RICO|QATAR|RWANDA|SAINT HELENA|SAINT KITTS AND NEVIS|SAINT LUCIA|SAINT PIERRE AND MIQUELON|SAINT VINCENT AND THE GRENADINES|SAO TOME AND PRINCIPE|SAUDI ARABIA|SENEGAL|SEYCHELLES|SIERRA LEONE|SINGAPORE|SOMALIA|SOUTH AFRICA|SRI LANKA|SUDAN|SURINAME|SWAZILAND|SYRIAN ARAB REPUBLIC|TAIWAN, PROVINCE OF CHINA|TAJIKISTAN|TANZANIA, UNITED REPUBLIC OF|THAILAND|TIMOR-LESTE|TOGO|TOKELAU|TRINIDAD AND TOBAGO|TUNISIA|TURKEY|TURKMENISTAN|TURKS AND CAICOS ISLANDS|UGANDA|UNITED ARAB EMIRATES|UNITED STATES|UNITED STATES MINOR OUTLYING ISLANDS|URUGUAY|UZBEKISTAN|VENEZUELA|VIETNAM|VIRGIN ISLANDS, U.S.|WESTERN SAHARA|YEMEN|ZAMBIA|ZIMBABWE".split('|'),
		AU : "ANTARCTICA|AUSTRALIA|FIJI|HEARD ISLAND AND MCDONALD ISLANDS|KIRIBATI|MARSHALL ISLANDS|MICRONESIA, FEDERATED STATES OF|NAURU|NEW ZEALAND|PALAU|PAPUA NEW GUINEA|SAMOA|SOLOMON ISLANDS|TONGA|TUVALU|VANUATU".split('|'),
		UK : "ANGUILLA|SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS|VIRGIN ISLANDS, BRITISH|UNITED KINGDOM".split('|'),
		EU : "ALAND ISLANDS|ALBANIA|ANDORRA|ARMENIA|AUSTRIA|BELARUS|BELGIUM|BOSNIA AND HERZEGOVINA|BOUVET ISLAND|BULGARIA|CAYMAN ISLANDS|CROATIA|CYPRUS|CZECH REPUBLIC|DENMARK|ESTONIA|FALKLAND ISLANDS (MALVINAS)|FAROE ISLANDS|FINLAND|FRANCE|FRENCH GUIANA|FRENCH POLYNESIA|FRENCH SOUTHERN TERRITORIES|GEORGIA|GERMANY|GIBRALTAR|GREECE|GUADELOUPE|HOLY SEE (VATICAN CITY STATE)|HUNGARY|ICELAND|IRELAND|ITALY|LATVIA|LIECHTENSTEIN|LITHUANIA|LUXEMBOURG|MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF|MALTA|MOLDOVA, REPUBLIC OF|MONACO|NETHERLANDS|NETHERLANDS ANTILLES|NORWAY|POLAND|PORTUGAL|REUNION|ROMANIA|RUSSIAN FEDERATION|SAN MARINO|SERBIA AND MONTENEGRO|SLOVAKIA|SLOVENIA|SPAIN|SVALBARD AND JAN MAYEN|SWEDEN|SWITZERLAND|UKRAINE|WALLIS AND FUTUNA".split('|')
	};
	
	// BC SPECIFIC FUNCTIONS //
	var BC = {
	
		ShoppingCart : {
			passTotal : function () {
				// add the current total price to the href of the checkout link as a hash //
				$('#catshopbuy').live('mousedown', function () {
					this.href = this.href + '#' + $.trim($('#invoicetotal').text().replace(/[^\d\.]/g, ''));
				});

			}
		},
		
		resolveCheckOut : function () { // follows the donnahay layout See: http://dhonline.smartwebmarketing.com.au/
			var $chooseCon = $('#choose-con'),
				$loginCon = $('#login-con'),
				$checkoutCon = $('#checkout-con'),
				$chooseRadios = $chooseCon.find('input:radio');		
			
			// isLoggedIn - must be declared above ex. var isLoggedIn = {module_isloggedin}
			if (!isLoggedIn) {	// if NOT logged in		
				
				$chooseCon.removeClass('hide');
				$checkoutCon.find('input[readonly]').not('#Amount').removeAttr('readonly');
				$chooseRadios.bind('click', function (e) {
					if ((1*this.value) === 1) {
						$checkoutCon.addClass('hide');
						$loginCon.removeClass('hide');
					}
					else {								
						$loginCon.addClass('hide');
						$checkoutCon.removeClass('hide');
					}
				});	
			}
			else { // if logged in		
				$checkoutCon.removeClass('hide');		
			}

			var amount = $.trim(window.location.hash.replace('#','')); // get Amount here
			if (amount !== '') {
				document.getElementById('Amount').value = amount;
			}	
		},
		
		usernameEqualtoEmail : function () {
			$('#Username').blur(function () {
				$('#EmailAddress').val(this.value);
			});

		},
		
		shippingEqualToBilling : function (_checkbox_selector) {
			//  <input type="checkbox" style="margin-left: 10px;" id="billing-shipping-checkbox" /><small>(Same as Billing details)</small>
			$(_checkbox_selector).bind('click', function () {
				if (!this.checked) {					
					$('#ShippingAddress, #ShippingCity, #ShippingState, #ShippingZip').val('');
					return;
				}				
				var items = ['Address','City','State','Zip'],
					len = items.length,
					i = 0;
				for (;i<len;i++) {
					$('#Shipping' + items[i]).val($('#Billing'+items[i]).val());
				}
				$('#ShippingCountry').find('option[value='+$('#BillingCountry').find('option:selected').val()+']').attr('selected', true);
					
			});
		},
		
		Dialog : {
			formError : function (_msg, _notForm) {
				// <div id="form-error" class="redb hide"></div> //
				var $dialogCon = $('#form-error');
				if ($dialogCon.length <= 0) { return; }				
				if (_notForm === undefined) {
				    $dialogCon.html('').hide();
					_msg = _msg.replace('\n', ''); // under observation
					var warnings = _msg.split('-'),
						warLen = warnings.length,
						html = '';					
					html += '<p>';
					html += '<h4 class="notice">You need to fill in these fields:</h4><br />';
					//html += '<img src="'+PATHS.IMG+'error_button.gif" alt="" style="float: left"/>';		
					html += '<ul id="warning-list">';	
					for (var i=0; i<warLen; i++) {						
						if (t(warnings[i]) === '') {continue;}
						html += '<li>' + t(Ttow.Util.entities(warnings[i])) + '</li>';
					}
					html += '</ul>';
					html += '</p>';	
					$(document.body).Ttow('scrollToMe'); 
					$dialogCon.html(html)
							  .slideDown();					
				}
				else {
					
				}				
			}
		},

		formFieldHighlight : function (_form) { 
			$(_form).find('input, textarea, select').bind({
				'focus' : function () {
					$(this).closest('tr').addClass('form-field-highlight');
				},
				
				'blur' : function () {
					$(this).closest('tr').removeClass('form-field-highlight');
				}
			});
		}
	};	
	
	var privates = {
		bodyClassHack : function () {
			var $body=$(document.body),browser=Ttow.Browser;
			/*@cc_on
			$body.addClass('ie');if(browser.msie6){$body.addClass('ie6 ie67 ie68 ie69');}
			else if(browser.msie7){$body.addClass('ie7 ie67 ie78 ie79');}
			else if(browser.msie8){$body.addClass('ie8 ie68 ie78 ie89');}
			else if(browser.msie9){$body.addClass('ie9');}
			return;@*/
			$body.addClass('not-ie');
			if(document.addEventListener){if(browser.mozilla){$body.addClass('moz');}
			else if(browser.chrome){$body.addClass('chrome');}
			else if(browser.safari){$body.addClass('safari');}
			else if(browser.opera){$body.addClass('opera');}
			else if(browser.ff2){$body.addClass('ff2');}}						
		},
		
		cookieHandler : function () {
			var cookie = $.cookie(CONFIG.COUNTRY_COOKIE);
			window.Apresvelo.Country = cookie || Apresvelo.extractCountryFromURL();
			window.Apresvelo.Domain = (function () {
				var c = window.Apresvelo.Country;
				if (c === CONFIG.COUNTRY.US) {					
					return CONFIG.DOMAIN.US;			
				}
				else if (c === CONFIG.COUNTRY.EU) {
					return CONFIG.DOMAIN.EU;
				}
				else if (c === CONFIG.COUNTRY.UK) {				
					return CONFIG.DOMAIN.UK;
				}
				else {					
					return CONFIG.DOMAIN.AU;
				}
			})();			
		},
		
		shoppingCartPollingTime:undefined,
		
		listenForShoppingCartReturn : function (_callback) {
			clearTimeout(privates.shoppingCartPollingTime);
			(function poll() { // im a big fan of this polling pattern!!! ^^....
				if ($('div.shop-cart').length || $('#catCartDetails').length) {// check if the shopping cart elements has been rebuilt by the BC ajax functions
					//alert($('div.shop-cart').length + '----' + $('#catCartDetails').length);
					_callback();
				}
				else {
					// waiting...
					privates.shoppingCartPollingTime = setTimeout(poll, 50);
					return;
				}				
			})();
		}
	};
	
	var E = {
		unloads : {			
			unload : function (e) {
				
			},			
			beforeunload : function (e) {
				$(this).unbind('unload');
					
			}			
		},
		
		numeric : function (e) {
			if (t(this.value) === '') {return;}
			if (!(/^[0-9,]+$/).test(t(this.value))) {
				this.value = '';					
				alert('Please enter a numeric value', 'warning');					
			}
		}								
	};
	
	window.Apresvelo = {				
		
		BC : BC, // expose the BC object
		
		CONFIG : CONFIG,
		
		loadEvents : function () {			
			//window unload events //
			$.root.delegate("a[href^='http://'], a[href^='https://']", 'mousedown', function () {
				$(window).unbind('unload').unbind('beforeunload');
			});			
			$(window).bind({				
				'unload' :  E.unloads.unload,
				'beforeunload' : E.unloads.beforeunload
			});			
			if (Ttow.Browser.msie8) {$('noscript').css('display', 'none');}			
			$.root.delegate('input.numeric', 'blur', E.numeric);
			
			/*@cc_on
				//See: http://kb.worldsecuresystems.com/598/bc_598.html#main_Hiding_the_red__x__in_IE_when_you_have_empty_image_fields_in_web_app_display
				$('img').live('error', function () {
					$(this).addClass('invisible');
				});
			@*/
			//Apresvelo.changeRegion($('#navsub_496231_475525').find('a'), true); // change region top menu declaration (top right drop down menu...)
			Apresvelo.changeRegion($('#navsub_496231_507009').find('a'), true); // change region top menu declaration (top right drop down menu...) LM: 03-17-11 [changed the menu id]
		},
		
		// set the region countries array...usuall used country select elements //
		setRegionCountries : function () {
			var currCountry = Apresvelo.extractCountryFromURL(
				((uri.indexOf('worldsecuresystems.com') === -1) ? uri : document.referrer)
			);				
			//INHALE
			if(uri.indexOf('worldsecuresystems.com') != -1) {
				Apresvelo.setupCookieFromReferrer();
				currCountry = window.Apresvelo.Country;
			}
			switch (currCountry) {
				case CONFIG.COUNTRY.US : window.Apresvelo.regionCountries = COUNTRY.US; break;						
				case CONFIG.COUNTRY.AU : window.Apresvelo.regionCountries = COUNTRY.AU; break;							
				case CONFIG.COUNTRY.UK : window.Apresvelo.regionCountries = COUNTRY.UK; break;							
				case CONFIG.COUNTRY.EU : window.Apresvelo.regionCountries = COUNTRY.EU; break;							
			}				
		},
		
		setCookieForRegionThenRedirectToDomain : function (_cookyValue) {
			var opt =  Apresvelo.CONFIG.COOKIE_OPTIONS,
				cooky = Apresvelo.CONFIG.COUNTRY_COOKIE,
				c = t(_cookyValue),				
				getIndexPage = function (_cook) {
					if (uri.indexOf('worldsecuresystems.com') > -1) {
						return '/index.htm?dom='+_cook; //pass the country as a query string cause i can't set it in worldsecuresystems.com
					}
					else {
						return '/index.htm';
					}
				};				
			$.cookie(cooky,null,CONFIG.COOKIE_OPTIONS_REMOVE); // remove the old cookie	
			//ClearCart(375939,0)			
			//$.cookie('CartID',null);			
			
			// redirect to the domain depending on the country saved in the cookie //
			// redirect them to the index.htm page...	
			if (c === CONFIG.COUNTRY.US) {					
				$.cookie(cooky, c, opt);				
				document.location = CONFIG.DOMAIN.US + getIndexPage(c);			
			}
			else if (c === CONFIG.COUNTRY.EU) {
				$.cookie(cooky, c, opt);
				document.location = CONFIG.DOMAIN.EU + getIndexPage(c);	
			}
			else if (c === CONFIG.COUNTRY.UK) {
				$.cookie(cooky, c, opt);
				document.location = CONFIG.DOMAIN.UK + getIndexPage(c);	
			}
			else {
				$.cookie(cooky, c, opt);
				document.location = CONFIG.DOMAIN.AU + getIndexPage(c);	
			}
		},
		
		changeRegion : function ($o, _showConfirm) {
			$o.click(function (e) {
				var c = $.trim(this.getAttribute('rel')).toLowerCase();			
				if (_showConfirm) { // for top menu
					//this should only occur when the billing address has changed and they have left the region. 
					//It then advises them to LOGIN and modify their account details to their new region Billing address. 
					//Then come back and re-set their region.
					if (!window.confirm('Please ensure that you have changed your billing address to your new region. If not, please login and modify your billing details. Proceed?')) {
						e.preventDefault();
						return false;	
					}
					c = $.trim($(this).find('span').text()).toLowerCase();
				}				
				Apresvelo.setCookieForRegionThenRedirectToDomain(c);				
				e.preventDefault();
				return false;
			});
		},
		
		extractCountryFromURL : function (_url) {
			_url = _url || uri; // shuld have really used document.domain...maybe in the future ;)...
			var c;			
			return $.trim((function () {
				try {
					c =  _url.match(/http(s)?:\/\/[^.]+\./)[0]
							  .replace(/http(s)?:\/\//, '')
							  .replace('.','')
							  .toLowerCase();
					return ((c.length > 2) ? CONFIG.COUNTRY.AU : c);		  
				}
				catch (e) {return CONFIG.COUNTRY.AU;}
			})());
		},
		
		setupCookieFromReferrer : function () {
			// At worldsecuresystems.com "apresvelo_country" cookie is lost
			// so try to retrieve it using the document.referrer
			// and then set the proper values for Apresvelo.Country and
			// Apresvelo.Domain	
			var ref = $.trim(document.referrer),
				pattern = Apresvelo.extractCountryFromURL(ref);
			if (pattern.length > 2) {
				pattern = CONFIG.COUNTRY.AU;
			}	
			//console.log(pattern);
			if(ref.indexOf('apresvelo.worldsecuresystems.com') != -1) {
				//INHALE
				// So, no cookie, no referrer, lets get to business.
				if(typeof Ttow.Qs.Country == 'undefined') {
				} else {
					pattern = Ttow.Qs.Country;
				}
			}
			//console.log(pattern);
			
			window.Apresvelo.Country = pattern;
			window.Apresvelo.Domain = (function () {
				var c = window.Apresvelo.Country;
				
				if (c === CONFIG.COUNTRY.US) {					
					return CONFIG.DOMAIN.US;			
				}
				else if (c === CONFIG.COUNTRY.EU) {
					return CONFIG.DOMAIN.EU;
				}
				else if (c === CONFIG.COUNTRY.UK) {				
					return CONFIG.DOMAIN.UK;
				}
				else {	
					
					return CONFIG.DOMAIN.AU;
				}
			})();
			
		},
		
		back2BaseDomain : function () {
			// when on checkoutpage(worldsecuresystems.com) domain name in the links href is change,
			// modify the href of all the links in the page back to its original domain name

			if($('#RecipientName').length && $('#RecipientEmail').length && $('#Message').length) {
				// Gift Voucher Page 
				$('a:not(#catshopcontinue)').attr('href', function (e) {
					if ($.trim(this.href.replace('#', '')) !== '') {
						return this.href.replace(document.domain, Apresvelo.Domain)
										.replace(/http(s)?:\/\//, '');
					}
					else {return this.href;}
				}); 
			} else {
				$('a').attr('href', function (e) {
					if ($.trim(this.href.replace('#', '')) !== '') {
						return this.href.replace(document.domain, Apresvelo.Domain)
										.replace(/http(s)?:\/\//, '');
					}
					else {return this.href;}
				});
			}
		},
		
		handleWorldSecureSystemStuff : function () {
			if (uri.indexOf('worldsecuresystems.com') > -1) {				
				Apresvelo.setupCookieFromReferrer(); // get the proper cookie....no calling of cookies here, just uses the referrer
				Apresvelo.back2BaseDomain();	// change the link values to the original domain
				
				/**/
				// fix the login form on the checkoutpage LM: 10-19-10 //
				var $checkouotLoginForm = $('#catseczoneform40660');
				if ($checkouotLoginForm.length) {
					$checkouotLoginForm.attr('action', function () {													
						var c = Apresvelo.getDomainName(Apresvelo.Country);		
						
						// replace the worldsecuresystems.com domain in the action attribute with 
						// the sites proper domain [ie. eu.apresvelo.com].
						// Its ok to use Apresvelo.Country here because it is 
						// generated inside Apresvelo.setupCookieFromReferrer()
						// not from the cookie itself.
						//return this.action.replace('https://'+document.domain, c)
						//				  .replace('https://'+document.domain, c)
						//				  .replace('.com:443', '.com'); // remove the port number on the destination page
						return this.action.replace('.com:80', '.com');
					});
				}
				/**/
			} else {
				// Getting error because it goes to worldsecuresystems.com:80 2011-07-06
				var $checkouotLoginForm = $('#catseczoneform40660');
				if ($checkouotLoginForm.length) {
					$checkouotLoginForm.attr('action', function () {													
						return this.action.replace('.com:80', '.com');
					});
				}
			}
		},
		
		// add the currency name relative to the region where the user logged in ie. EURO, USD, etc...
		addCurrencyName : function (_useReferrerForDomain) {
			var $curr = $('.apres-currency');
			if ($curr.length<1) {
				return;
			}
			var currency = (function () {
				var c = $.trim(Apresvelo.extractCountryFromURL(((_useReferrerForDomain) ? document.referrer : uri)));
				//INHALE
				if(_useReferrerForDomain) {
					Apresvelo.setupCookieFromReferrer();
					c=window.Apresvelo.Country; 
				}
				if (c === CONFIG.COUNTRY.US) {return 'USD';}
				else if (c === CONFIG.COUNTRY.EU) {return 'EURO';}
				else if (c === CONFIG.COUNTRY.UK) {return 'GBP';}
				else {return 'AUD';}
			})();
			
			$curr.each(function () {
				var $me = $(this),
					txt = $.trim($me.text()).replace(/USD|EURO|GBP|AUD/, '').replace(/\s*$/, '');					
				$me.text(txt + ' ' + currency);
			});
		},
		
		addInitalValueForCountrySelectInShoppingCart : function () { // for shipping country
			var $countrySelect = $('#shippingCountry'),
				defaultVal = '-- Please choose your country --',
				currSelected = $countrySelect.find('option:selected').val();				
			if ($.trim(currSelected) === '') {
				currSelected = 'no-value';
			}
			//console.log(currSelected);
			// add an initial value of blank to the shipping country select box				
			$countrySelect.html($('#apres-shipping-countries').html())
						  .find('option[value='+currSelected+']')
							.attr('selected', true);															
		},
		
		// place all modifications for the cart after it is refreshed by ajax here... //
		cartModificationsAfterResponse : function () { 
			Apresvelo.addCurrencyName();		
			//add a dummy value for country then remember the value selected...
			Apresvelo.addInitalValueForCountrySelectInShoppingCart();												
		},
		
		cartListener : function () {			
			if (!Ttow.Browser.msie) { // for non IE browsers...that behaves
				$.root.delegate('div.productitemcell a, #catshopclear', 'click', function () {
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});
				});
				$.root.delegate('div.productitemcell input.cartInputText,#DiscountCode,#GiftVoucher,#shippingCountry,#ShippingOptions,#shippingState', 'change', function () {				
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});
				});
			}
			else { // Do IE hacks here...for some reason the events used above doesn't work in ie @__@'	
				$.root.undelegate('div.productitemcell a, #catshopclear', 'click');
				$.root.undelegate('div.productitemcell input.cartInputText,#DiscountCode,#GiftVoucher,#shippingCountry,#ShippingOptions', 'change');								
				/*
					// BC functions i have to override inorder for this to work in ie //
					UpdateItemQuantity(this.value,344422,0,836493,680203,'','AU');return false;
					UpdateItemQuantity(0,344422,0,836493,680203,'','AU');return false;
					ApplyDiscountCode(this.value,344422,0);return false;
					ApplyGiftVoucher(this.value,344422,0);return false;
					SetShippingCountry(this.value,344422,0);
					UpdateShipping(this.value,344422,0);
					ClearCart(344422,0);return false;
					ApplyTaxRate
				*/
				// keep a copy of the BC functions here //
				var __UpdateItemQuantity = UpdateItemQuantity,
					__ApplyDiscountCode = ApplyDiscountCode,
					__ApplyGiftVoucher = ApplyGiftVoucher,
					__SetShippingCountry = SetShippingCountry,
					__UpdateShipping = UpdateShipping,
					__ClearCart = ClearCart,
					__ApplyTaxRate = ApplyTaxRate;
				
				// override the bc functions on the shopping cart...to add my own code //
				window.ApplyTaxRate = function (a,b,c,d,e) {
					__ApplyTaxRate(a,b,c,d,e);
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});
				};
				
				window.UpdateItemQuantity = function (a,b,c,d,e,f,g) {					
					__UpdateItemQuantity(a,b,c,d,e,f,g);
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});
				};				
				window.ApplyDiscountCode = function (a,b,c) {					
					__ApplyDiscountCode(a,b,c);
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});	
				};				
				window.ApplyGiftVoucher = function (a,b,c) {					
					__ApplyGiftVoucher(a,b,c);
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});	
				};				
				window.SetShippingCountry = function (a,b,c) {
					__SetShippingCountry(a,b,c);
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
						/** /
						if ($('#shippingCountry').find('option:selected').val() == 'no-value') {
							//alert($('#shippingCountry').find('option:selected').val());
							$('#shippingCountry').find('option:eq(0)').attr('selected', true);
						}
						/**/
					});					
				};				
				window.UpdateShipping = function (a,b,c) {
					__UpdateShipping(a,b,c);
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});	
				};				
				window.ClearCart = function (a,b) {
					__ClearCart(a,b);
					privates.listenForShoppingCartReturn(function () {
						Apresvelo.cartModificationsAfterResponse();
					});
				};
			}
		},
		
		// this scripts will run on the shopping cart page //
		doShoppingCartStuff : function () { 
			if ($('div.shop-cart').length && uri.indexOf('OrderRetrievev2.aspx') > -1) {
				Apresvelo.cartListener();
				window.Apresvelo.selectedCountry = ''; //define a global variable here to store the selected country, Currently only used in shoppingcart page.	
				// add an initial value of blank to the shipping country select box
				Apresvelo.addInitalValueForCountrySelectInShoppingCart();
				
				// check if a shipping country has been chosen...if not alert warning...
				$('#catshopbuy').live('click', function (e) {
					if ($('#shippingCountry').find('option:selected').val() === 'no-value') {
						alert('Please choose your shipping country');
						e.preventDefault();
						return false;
					}
					this.href = this.href+'#'+Apresvelo.extractCountryFromURL();
				});
				
				$('#shippingCountry').find('option:eq(0)')
										.attr('selected', true)
										.end()
									 .live('change', function () {
										 window.Apresvelo.selectedCountry = $(this).find('option:selected').val();
									 });
				if (Ttow.Browser.msie) {
					setTimeout(function () {
						$('#shippingCountry').find('option:eq(0)').attr('selected', true);
					}, 500);
				}
				
				$('#ShippingOptions').attr('disabled', true);								
				$('#shippingCountry').live('change', function () {
					//alert($(this).find('option:selected').val());
					if ($(this).find('option:selected').val() !== 'no-value') {						
						$('#ShippingOptions').attr('disabled', false);
					}
					else {
						privates.listenForShoppingCartReturn(function () {														
							$('#shippingCountry').find('option:eq(0)').attr('selected', true);							
						});
						$('#ShippingOptions').attr('disabled', true);
					}
				});
				
				$('div.shippingStateDiv').remove(); // LM: 10-26-10
				
			}			
		},
		
		// this scripts will run on the checkout page //
		doCheckoutPageStuff : function () {
			if (($('#checkoutform').length || $('#radiodiv').length) && uri.indexOf('OrderRetrievev2.aspx') > -1) {
				Apresvelo.removeUnneededCountries($('#BillingCountry')); //show only the countries for the region on the billing country field
				$('#BillingCountry').prepend('<option selected="selected" value="no-value"> -- Please choose your country -- </option>')
									.css('width','220px');
													
				if (Ttow.Browser.msie) {
					setTimeout(function () {
						$('#BillingCountry').find('option[value=no-value]').attr('selected', true);
					}, 500);
				}					
									
				/** /
				var $shippingCountry = $('#ShippingCountry'),
					chosenShippingCountry = $shippingCountry.find('option:selected').val();	// get the initial selected value			
				$shippingCountry.html($('#apres-shipping-countries').html()); // hack i have to do to show all the countries in the shipping field
				$shippingCountry.find('option[value='+chosenShippingCountry+']').attr('selected', true); // select the country selected in the shopping cart page
				/**/			
				Apresvelo.addCurrencyName(true);											
			}
		}, 
		
		// removes the countries that are not in the current region/domain
		removeUnneededCountries : function (_$select) {
			if (!_$select.is('select')) {
				throw 'object passed to Apresvelo.removeUnneededCountries() is not a <select> element. Its a <'+_$select.get(0).tagName.toLowerCase()+'> element.';				
			}					

			countries = window.Apresvelo.regionCountries;	
			_$select.find('option').each(function () {
				var $me = $(this);
				if ($.inArray(t($me.text()), countries) < 0) {
					$me.remove();
				}
			});
		},
		
		getDomainName : function (_domainCode) {
			var dc = t(_domainCode).toLowerCase();
			switch (dc) {
				case CONFIG.COUNTRY.US : return CONFIG.DOMAIN.US ;						
				case CONFIG.COUNTRY.AU : return CONFIG.DOMAIN.AU;							
				case CONFIG.COUNTRY.UK : return CONFIG.DOMAIN.UK;			
				case CONFIG.COUNTRY.EU : return CONFIG.DOMAIN.EU;
				default : return CONFIG.DOMAIN.AU;  	
			}		
		},
		
		redirectIfUserAlreadyHasACookie : function () { // if the site keeps reloading in a loop...then the cause of the  bug should be inside this method.
			if (uri.indexOf('worldsecuresystems.com') > -1) {return;}			
			if (Ttow.Qs.dom) {
				$.cookie(Apresvelo.CONFIG.COUNTRY_COOKIE, $.trim(Ttow.Qs.dom), Apresvelo.CONFIG.COOKIE_OPTIONS);
			}
			var cooky = $.cookie(Apresvelo.CONFIG.COUNTRY_COOKIE), //cookie [au,us,eu,uk]
				currDomain = Apresvelo.extractCountryFromURL();	   // current domain [au,us,eu,uk]			
			if (cooky) {
				cooky = t(cooky);
				//window.console.log(currDomain+'    '+cooky);//return;
				if (cooky !== currDomain) { //check if the user already has a cookie and is not on the same domain..then redirect him/her to the proper domain
					$.cookie(Apresvelo.CONFIG.COUNTRY_COOKIE, cooky, Apresvelo.CONFIG.COOKIE_OPTIONS);
					if (uri.indexOf('choose-country') > -1) {						
						window.location.href = 'http://'+document.domain+'/index.htm'; // to prevent infinite redirection loop...
					}
					else {											  
						window.location.href = uri.replace(/http(s)?:\/\//, '')
												  .replace(document.domain, Apresvelo.getDomainName(cooky));						  
					}
					
				}
			}// else cookie was not set				
		},
		
		deleteAllCookiesExceptFor : function (_arr) { // takes in a parameter of cookies that should not be deleted.
			// might come in handy, removing all cookies for current domain
			// See: http://stackoverflow.com/questions/179355/clearing-all-cookies-with-javascript
			var cookies = document.cookie.split(";");
			_arr = ((!$.isArray(_arr)) ? [_arr] : _arr); //whitelist...
			for (var i = 0; i < cookies.length; i++) {
				var cookie = cookies[i];
				var eqPos = cookie.indexOf("=");
				var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
				if ($.inArray(name, _arr) < 0) { //check if cookie is in the white list...
					document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
				}				
			}
		},
		
		tempTellAfriendFix : function () { // quick fix for the tell-a-friend form...i can't find the tell-a-friend layout in BC. todo: fix this 10-11-10
			if (uri.indexOf('ReferAFriendProcess.aspx') > -1) {
				$('#RFFullName, #RFEmailAddress').attr('readonly', false).val('');
			}
		},
		
		subscribeRedirect : function() {
			var listid = "23995";
			

			$('#SubscribeCountry').hide();
			switch(Apresvelo.Country) {
				case "au": listid="39963"; break;
				case "eu": listid="39407"; break;
				case "uk": listid="39965"; break;
				case "us":
					listid="39964";
					
					if($('div.newsletter-box span.us-sub-heading').length) {
						$('div.newsletter-box span.sub-heading').hide();
						$('div.newsletter-box span.us-sub-heading').show();
					}
					
					$('#SubscribeCountry').show().change(function() {
						switch($(this).children('option:selected').val()) {
							case "africa": listid="39459"; break;
							case "asia": listid="39460"; break;
							case "middleeast": listid="39462"; break;
							case "northamerica": listid="39964"; break;
							case "southamerica": listid="39463"; break;
							default: listid="37664"; break;
						}
						$('#subscribeform').attr('action',"/CampaignProcess.aspx?ListID=" + listid + "&OPTIN=true");
					});
				break;
			}
			$('#subscribeform').attr('action',"/CampaignProcess.aspx?ListID=" + listid + "&OPTIN=true");
		},
		
		doHomePage : function() {
			if($('#diaporama').length) {
				//$.getScript('/js/jquery.nivo.slider.pack.js', function(data, textStatus){
					//var startslide = Math.floor(Math.random() * $('#diaporama img').length);
					$('#diaporama').nivoSlider({
						effect: 'sliceDown', // sliceDown,sliceDownLeft,sliceUp,sliceUpLeft,sliceUpDown,sliceUpDownLeft,fold,fade,random,slideInRight,slideInLeft,boxRandom,boxRain,boxRainReverse,boxRainGrow,boxRainGrowReverse
						slices: 15, // For slice animations
						boxCols: 8, // For box animations
						boxRows: 4, // For box animations
						animSpeed: 800, // Slide transition speed
						pauseTime: 5000, // How long each slide will show
						startSlide: 0, // Set starting Slide (0 index)
						directionNav: true, // Next & Prev navigation
						directionNavHide: true, // Only show on hover
						controlNav: true, // 1,2,3... navigation
						controlNavThumbs: false, // Use thumbnails for Control Nav
						controlNavThumbsFromRel: false, // Use image rel for thumbs
						controlNavThumbsSearch: '.jpg', // Replace this with...
						controlNavThumbsReplace: '_thumb.jpg', // ...this in thumb Image src
						keyboardNav: true, // Use left & right arrows
						pauseOnHover: true, // Stop animation while hovering
						manualAdvance: false, // Force manual transitions
						captionOpacity: 0.8, // Universal caption opacity
						prevText: '', // Prev directionNav text
						nextText: '', // Next directionNav text
						beforeChange: function(){}, // Triggers before a slide transition
						afterChange: function(){}, // Triggers after a slide transition
						slideshowEnd: function(){}, // Triggers after all slides have been shown
						lastSlide: function(){}, // Triggers when last slide is shown
						afterLoad: function(){} // Triggers when slider has loaded
					});
				//});
			}
		},
		
		init : function () {
			privates.bodyClassHack();
			Apresvelo.setRegionCountries(); // set the proper region countries array...used to change the countrye select boxs
			Apresvelo.loadEvents();			
			Apresvelo.addCurrencyName(); // add currency name to prices			
			Apresvelo.doShoppingCartStuff();
			Apresvelo.handleWorldSecureSystemStuff(); // if page is in worldsecuresystems.com...do some stuff
			Apresvelo.doCheckoutPageStuff();
			
			// do things with cookies here LM: 11-09-10//
			if (!$.isFunction($.cookie)) {				
				Ttow.imports('/js/jquery.cookie.js');
			}			
			privates.cookieHandler();
			
			//check if the user already has a cookie and is not on the same domain..then redirect him/her to the proper domain //
			Apresvelo.redirectIfUserAlreadyHasACookie(); 
			
			//Tell a Friend quick fix...should be replaced...//
			Apresvelo.tempTellAfriendFix();
			 
			Apresvelo.subscribeRedirect();
			
			Apresvelo.doHomePage();
			
			
			
			if($('#RecipientName').length && $('#RecipientEmail').length && $('#Message').length) {
				// Gift Voucher page...
				//if(typeof Ttow.Qs.Country == 'undefined') {
					var c = $.trim(Apresvelo.extractCountryFromURL(document.referrer));
					//var newurl = document.location.href.replace('SelectedRateKey','Country=' + c + '&SelectedRateKey');
					//document.location.href=newurl;
					if($('#catshopcontinue').length) {
						$('#catshopcontinue').attr('href',function(i,val) {
							return val + '&Country=' + c; 
						});
					}
				//}
			}
		}
		
	};

	Apresvelo.init();	// initializes all the script above...
	
	
	$(window).load(function() {
		Oshoplang['OutOfStock'] = 'Please choose your size from the drop down list';
	});
});



