// Copyright (c) 2008 Mirchev Ideas Ltd. All rights reserved.

SC = new function()
{
	this.Home = {};
	this.Cart = {};
	this.Wizard = {};
	this.Util = {};
	this.storeRoot = '';
};

SC.Home = new function()
{
	this.showErrors = function(errors)
	{
		for (var property in errors) {
			$('[name=' + property + ']').addClass('input-error').after('<div class="error-note">' + errors[property] + '</div>');
		}
	}
}

SC.Util = new function() {

	this.filterFormStates = function()
	{
		var statesInputs = $('.state');
		var countriesInputs = $('.country');
		var num = statesInputs.length > countriesInputs.length ? countriesInputs.length : statesInputs.length;
	
		for (var i=0; i < num; i++) {
			if ((countriesInputs.get(i).name == this.name) || (typeof this.nodeName == 'undefined'))
				SC.Util.filterStates(statesInputs.get(i), 0, countriesInputs.get(i).value, states);
		}
	}
	
	this.toggleShippingAddress = function() 
	{
		var customerShipToBillingAddress = document.getElementById('CustomerShipToBillingAddress');
		if (customerShipToBillingAddress == undefined)
			return;
		
		if (customerShipToBillingAddress.checked) 
			$('#shippingAddress').hide();
		else
			$('#shippingAddress').show();
	}
	
	this.filterBillingStates = function() 
	{
		if (typeof states == 'undefined')
			return;
		
		var selectControl = $('#CustomerBillingState')[0];
		var originalValue = $('#OriginalCustomerBillingState').val();
		var filterByValue = $('#CustomerBillingCountry').val();
		
		SC.Util.filterStates(selectControl, originalValue, filterByValue, states);
	}
	
	this.filterShippingStates = function() 
	{
		if (typeof states == 'undefined')
			return;
		
		var selectControl = $('#CustomerShippingState')[0];
		var originalValue = $('#OriginalCustomerShippingState').val();
		var filterByValue = $('#CustomerShippingCountry').val();
	
		SC.Util.filterStates(selectControl, originalValue, filterByValue, states);
	}

	this.filterStates = function(selectControl, selectedStateId, countryId, statesArray)
	{
		if (selectControl == undefined)
			return;
		
		if (countryId == undefined)
			countryId = 0;
		
		// if the data array is available
		if (typeof statesArray == 'undefined')
			return;
		
		if (statesArray[countryId] == undefined) {
			selectControl.options.length = 0;
			selectControl.disabled = true;
			return;
		}
		selectControl.disabled = false;
	
		if ((selectedStateId == 0) && (selectControl.selectedIndex >= 0))
			selectedStateId = selectControl.options[selectControl.selectedIndex].value;
	
		selectControl.options.length = 0;
		for (var stateId in statesArray[countryId]) {
			selectControl.options[selectControl.length] = new Option(statesArray[countryId][stateId], stateId);
			if (stateId == selectedStateId)
				selectControl.options[selectControl.length-1].selected = true;
		}
	}
	
	this.loadFile = function(filename, type)
	{
		if (type == 'css') {
			var elem = document.createElement('link');
			elem.setAttribute('rel', 'stylesheet');
			elem.setAttribute('type', 'text/css');
			elem.setAttribute('href', filename);
		} else {
			elem = document.createElement('script')
  			elem.setAttribute('type', 'text/javascript')
  			elem.setAttribute('src', filename)
 		}
		document.getElementsByTagName('head')[0].appendChild(elem);
	}
	
	this.addQueryParams = function(url, params)
	{
		if (url.indexOf('#') == 0)
			return '?' + params + url;
		
		url = url.split('#');
		var hash = '';
		if (url.length > 1)
			hash = '#' + url[1];
		url = url[0];
		
		if (url.indexOf('?') == -1)
			return url + '?' + params + hash;
		
		url = url.split('?');
		// Overwriting of the variable is not handled.
		// If an older value is set it will remain.
		return url[0] + '?' + params + '&' + url[1] + hash;
	}
	
	this.getAbsolutePath = function(relativePath)
	{
//		var baseHref = document.getElementsByTagName('base');
//		if (baseHref && baseHref[0] && baseHref[0].href) {
//			if (baseHref[0].href.substr(baseHref[0].href.length-1) == '/' && relativePath.charAt(0) == '/')
//				relativePath = relativePath.substr(1);
//			relativePath = baseHref[0].href + relativePath;// relativePath is now actually absolute
//		}
		return relativePath;
	}

	this.Tabs = function(toShow){
		//var toShow = '#product-detailed-description';
		$('.tab-content').hide();
		
		$(toShow).show();
		$('.tabs-menu a').filter(function () {return $(this).attr("href") == toShow;}).parent().addClass('active');
		$('.tabs-menu a').click(function(){
			$('.tab-content').hide().filter(this.hash).fadeIn();
			$('.tabs-menu li.active').removeClass('active');
			$(this).parent().addClass('active');
			return false;
		});
	}

	this.postSubmit = function (target, query) {
		var parts = query.split('&');
		var form = $('<form action="' + target + '" method="post" id="scUtilPostSubmitForm" />');
		for (i in parts) {
			parts[i] = parts[i].split('=');
			var varName = parts[i].shift();
			var varValue = parts[i].join('=');
			var input = $('<input type="hidden" />');
			input.attr('name', decodeURI(varName));
			input.attr('value', decodeURI(varValue));
			form.append(input);
		}
		$('body').append(form);
		$('#scUtilPostSubmitForm').submit();
	}
	
	this.inArray = function(str, arr) {
		for (var key in arr) {
			if (typeof(arr[key]) == 'function') {
				continue;
			}
			if (arr[key] == str) {
				return true;
			}
		}
		return false;
	}
}

// Handle language and currency changes
$(function() {
	// Language drop-down
	$('#UILanguage').change(function() {
		var url = window.location.search;
		url = url.replace(/&?UILanguage=../g, '');
		url = SC.Util.addQueryParams(url, 'UILanguage=' + this.value);
		window.location.search = url;
	});
	
	// Currency drop-down
	$('#CurrencyID').change(function() {
		var url = window.location.search;
		url = url.replace(/&?CurrencyID=\d+/g, '');
		url = SC.Util.addQueryParams(url, 'CurrencyID=' + this.value);
		window.location.search = url;
	});
	
	// Product sort drop-down
	$("#ProductSort").change(function() {
		var redirectLocation = SC.Util.addQueryParams(SC.Home.selfUrl, "ProductSort=" + this.value);
		document.location.href = SC.Util.getAbsolutePath(redirectLocation);
	});
	
	// Top menu highlighting / hover
	path = window.location.href.substring(SC.storeRoot.length);
	
	if (path == '')
		path = 'index.php';
		
	$("#main-menu a").each(function() {
		href = $(this).attr("href");
		
		if (href.indexOf(':') > -1) {
			href = href.substring(SC.storeRoot.length);
		}
		if (href == '/')
			href = 'index.php';
		
		href = href.substring(href.indexOf('/') + 1);
		if (href == path)
			$(this).parent('li').addClass("current");
			
		if (href == undefined)
			return;
		
		// Highlight the links to forms
		if (href.substring(0,9) == 'form.php')
			$(this).parent('li').addClass("current");;
	});
	$("#main-menu a").hover(function() {
		$(this).parent('li').addClass('active');
	},
	function() {
		$(this).parent('li').removeClass('active');
	}
	);
	
	// Forms
	SC.Util.filterFormStates();
	$(".country").change(SC.Util.filterFormStates);
	
	// Addresses
	if (typeof states != 'undefined') {
		SC.Util.filterBillingStates();
		SC.Util.filterShippingStates();
		SC.Util.toggleShippingAddress();
		$("#CustomerBillingCountry").change(SC.Util.filterBillingStates);	
		$("#CustomerShippingCountry").change(SC.Util.filterShippingStates);
		$("#CustomerShipToBillingAddress").click(SC.Util.toggleShippingAddress);
	}
	
	// IE6 flicker fix
	if ($.browser.msie && /6.0/.test(navigator.userAgent))
		document.execCommand("BackgroundImageCache", false, true);
});
