/* 
	Tumbleweed Base Object
	LM: 11-05-10 

*/
jQuery(function ($) {
	$.root = $(document);	
	var uri = window.location.href,
		t = function (_s) { return $.trim(_s); },
		byId = function (_id) {return document.getElementById(_id);};
		
	var CONFIG = {
		BASE_URL : 'tumbleweed.com.au'
	};	
	
	// 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');}}						
		}
		
	};
	
	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.Tumbleweed = {				
		
		BC : BC, // expose the BC object
		
		
		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');
				});
			@*/
			
		},
		
		
		back2BaseDomain : function () {
			// when on checkoutpage(worldsecuresystems.com) domain name in the links href is changed,
			// modify the href of all the links in the page back to its original domain name
			$('a').attr('href', function (e) {
				if ($.trim(this.href.replace('#', '')) !== '') {
					return this.href.replace(document.domain, CONFIG.BASE_URL)
									.replace(/http(s)?:\/\//, 'http://');
				}
				else {return this.href;}
			});
		},		
		
		handleWorldSecureSystemStuff : function () {
			if (uri.indexOf('worldsecuresystems.com') > -1) {				
					
			}			
		},
		
		// this scripts will run on the shopping cart page //
		doShoppingCartStuff : function () { 
			if ($('table.cart').length && uri.indexOf('OrderRetrievev2.aspx') > -1) {
				
			}			
		},
		
		// this scripts will run on the checkout page //
		doCheckoutPageStuff : function () {
			
		}, 
		
		showPreviewImageLocation : function () {
			if (uri.indexOf('/shop-online/spare-parts/') === -1) {return;}
			if (!$('#img-preview').length) {
				var imghtml = '<div class="hide align-c" id="img-preview-con">'+
							'<br /><label id="preview-prod-name" class="align-c b"></label>'+
							'<br /><br /><img id="img-preview" src="" />'+
							'</div>'+
						    '';
				$('div.r_col').append(imghtml);				
			}
			
			$('#img-preview').bind('error', function () { 
				$(this).parent().addClass('hide'); //hide container div when there is no image
			});
			
			$.root.delegate('div.smallprod', 'mouseenter', function (e) {
				var p = this.getAttribute('rel').split('|||');
				$('#preview-prod-name').text(p[1]);
				$('#img-preview').attr('src', '/images/spare-parts/'+p[0]);
				$('#img-preview-con').removeClass('hide');
			});
			
		},
		
		init : function () {
			privates.bodyClassHack();
			Tumbleweed.loadEvents();
			Tumbleweed.showPreviewImageLocation();	
						
		}
		
	};

	Tumbleweed.init();	// initializes all the script above...
});
