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

SC = new function()
{
	this.Home = {};
	this.Cart = {};
	this.Wizard = {};
	this.Util = {};
	this.ML = {}; // Store ML phrases used in JS.
	this.Login = {};
	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 (typeof(customerShipToBillingAddress) == 'undefined')
			return;
		if (customerShipToBillingAddress === null)
			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 (typeof selectControl == 'undefined')
			return;
		
		if (typeof countryId == 'undefined')
			countryId = 0;
		
		// if the data array is available
		if (typeof statesArray == 'undefined')
			return;
		
		if (typeof(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 key in statesArray[countryId]) {
			var stateId = statesArray[countryId][key][0];
			selectControl.options[selectControl.length] = new Option(statesArray[countryId][key][1], stateId);
			if (stateId == selectedStateId)
				selectControl.options[selectControl.length-1].selected = true;
		}
	}
	
	this.attachAddressEvents = function()
	{
		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);
		}
	}
	
	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.
		var otherParams = '';
		if (url[1] && (typeof(url[1]) != 'undefined')) {
			otherParams = '&' + url[1];
		}
		return url[0] + '?' + params + otherParams + 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;
	}
	
	this.attachDropDown = function (target, direction) {
		var stepOver = 1; // The number of pixels of the upper box that are going to cover its parent.
		$(target).hover(
			function () {
				var firstUls = $(this).find('ul:first');
				firstUls.show();
				
				if (direction == 'right') {
					var positionLeft = $(this).position().left - stepOver + $(this).outerWidth();
					var offsetLeft = $(this).offset().left - stepOver + $(this).outerWidth();
					// Find the position that the box is going to end in.
					var wouldEnd = offsetLeft + firstUls.outerWidth();
					
					// If the box ends out of the body we move the box on the left side.
					if (wouldEnd > $('body').innerWidth()) {
						positionLeft = $(this).position().left - firstUls.outerWidth() + stepOver;
					}
					
					firstUls.css('position', 'absolute')
						.css('top', ($(this).position().top - 1) + 'px')
						.css('left', positionLeft + 'px');
				} else if (direction == 'below') {
					var positionTop = $(this).position().top - stepOver + $(this).outerHeight();
					var positionLeft = $(this).position().left - stepOver;
					var offsetTop = $(this).offset().top - stepOver + $(this).outerHeight();
					// Find the position that the box is going to end in.
					var wouldEnd = offsetTop + firstUls.outerHeight();
					
					// If the box ends out of the body we move the box on the up side.
					if (wouldEnd > window.innerHeight) {
						positionTop = $(this).position().top - firstUls.outerHeight() + stepOver;
					}
					
					firstUls.css('position', 'absolute')
						.css('top', positionTop + 'px')
						.css('left', positionLeft + 'px');
				}
			},
			function () {
				$(this).find('ul:first').hide();
			}
		);
	}
	
	this.attachDropDownBoxCategories = function (boxId, allCategoriesText) {
		if  ($('#box-' + boxId).parents('.h-column').length > 0) {

			//Shortens the list of categories and adds view all categories drop down
			$('.dd-categories-box > ul > li').each(function(index) {
				var catSchemeNumber = index + 1; 
				var catTopLevelWidth = $(this).width();
				$(this).width(catTopLevelWidth);
				$(this).addClass('dd-categories-colorSchema' + catSchemeNumber );
			});
			
			
			var ddListHtml = $('#box-' + boxId + ' > ul' ).html();
			var ddViewAllHtml = '<li class="ddViewAllLink"><a href="#">' + allCategoriesText + '</a><ul class="allCategoriesDD">' + ddListHtml + '</ul></li>';
			
			ddListHtml = ddListHtml + ddViewAllHtml;
			$('#box-' + boxId + ' > ul' ).html(ddListHtml);
					
			var ddViewAllWidth = $('#box-' + boxId + ' > ul > li.ddViewAllLink').width(); 
			var ddListWidth = $('#box-' + boxId + ' > ul').width();
			var ddListWidthShort = ddListWidth - ddViewAllWidth; 
			var ddListNewContainerWidh = 0;
			
			$('#box-' + boxId + ' > ul > li:not(.ddViewAllLink)').each(function() {
				ddListNewContainerWidh = ddListNewContainerWidh + $(this).width();
				if ( ddListNewContainerWidh < ddListWidthShort) {
					$(this).show();
				}
			});
			
			var stepOver = 0; // The number of pixels of the upper box that are going to cover its parent.
			
			
			$('#box-' + boxId + ' > ul > li.ddViewAllLink > ul > li').each(function(index) {
				if ((index + 1)%5 == 0) {
					$(this).after('<li class="clear"></li>');
				}
				ddViewAllHtmlWidthCount = ddViewAllHtmlWidthCount + 1;
			});
			
			var ddViewAllHtmlWidthCount = 5;
			var ddViewAllColumnsWidth = 180;  
		    ddViewAllHtmlWidth = ddViewAllHtmlWidthCount * ddViewAllColumnsWidth;
			$('#box-' + boxId + ' > ul > li.ddViewAllLink > ul').css('width', ddViewAllHtmlWidth);
			
			$('#box-' + boxId + ' > ul > li.ddViewAllLink').hover(
				function() {
					$('>ul', this).show();
				},
				function() { 
					$('>ul', this).hide();
				}
			);
			
			$('#box-' + boxId + ' > ul > li:not(.ddViewAllLink)').hover(
				function () {
					var firstUls = $(this).find('ul:first');
					firstUls.show();
					
					var positionLeft = $(this).position().left - stepOver;
					var positionTop = $(this).position().top + 34;
					var offsetLeft = $(this).offset().left - stepOver + $(this).outerWidth();
					// Find the position that the box is going to end in.
					var wouldEnd = offsetLeft + firstUls.outerWidth();
					
					// If the box ends out of the body we move the box on the left side.
					if (wouldEnd > $('body').innerWidth()) {
						positionLeft = $(this).position().left - firstUls.outerWidth() + stepOver;
					}
					
					firstUls.css('position', 'absolute')
						.css('top', positionTop + 'px')
						.css('left', positionLeft + 'px');
				},
				function () {
					$(this).find('ul:first').hide();
				}
			);
			
		} else {
				var stepOver = 1; // The number of pixels of the upper box that are going to cover its parent.

				$('#box-' + boxId + ' ul li').hover(
					function () {
						var firstUls = $(this).find('ul:first');
						firstUls.show();
						
						var positionLeft = $(this).position().left - stepOver + $(this).outerWidth();
						var offsetLeft = $(this).offset().left - stepOver + $(this).outerWidth();
						// Find the position that the box is going to end in.
						var wouldEnd = offsetLeft + firstUls.outerWidth();
						
						// If the box ends out of the body we move the box on the left side.
						if (wouldEnd > $('body').innerWidth()) {
							positionLeft = $(this).position().left - firstUls.outerWidth() + stepOver;
						}
						
						firstUls.css('position', 'absolute')
							.css('top', ($(this).position().top - 1) + 'px')
							.css('left', positionLeft + 'px');
					},
					function () {
						$(this).find('ul:first').hide();
					}
				);		
		}
	}
}

SC.Login = new function()
{
	this.RedirectOnLogin = '';
}

// 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 select 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;
	});
	// Currency selector drop-down
	$('.currency-selector').click(function() {
		$('#CurrencyID').val($(this).attr('id').split('_')[1]).change();
	});
	
	// 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);
	});
	
	// Product records per page drop-down
	$("#recordsPerPage").change(function() {
		var redirectLocation = SC.Home.selfUrl.replace(/&?recordsPerPage=\d+/g, '');
		redirectLocation = SC.Util.addQueryParams(redirectLocation, "recordsPerPage=" + this.value);
		document.location.href = SC.Util.getAbsolutePath(redirectLocation);
	});
	
	// Category Page - Subcategories
	$('#category-page #subcategories .subcategory:last-child').addClass('last-subcategory');
	$('#category-page #subcategories .subcategory').each(function(index) {
		counter = index + 1;
		if ( counter % 2 == 0) {
		 $(this).addClass('even-subcategory');
		}
	});
	$('#category-page #subcategories .even-subcategory:last').addClass('last-even-subcategory');
	
	// Category Page - Grid View - Cells
	$('#category-page .grid tr td.grid-vertical-space:last-child').addClass('last-vertical-space');
	
	// Forms
	SC.Util.filterFormStates();
	$(".country").change(SC.Util.filterFormStates);
	
	// Main menu submenus last element
	$('#main-menu li ul li:last-child').addClass('last-submenu');
	
	// Active Filters Box - Last Row
	$('#activeFiltersReset .row:last-child').addClass('last-filter-row');
	
	// Addresses
	SC.Util.attachAddressEvents();
	
	// Emails validation
	$('input[type=text].email')
		.each(function () {
			var emailInput = $(this);
			$(this).parents('form:first') // find the form that the input is contained in
				.bind('submit', function () {
					var regex = /^.+@.+$/;
					if (!regex.test(emailInput.val())) {
						alert(SC.ML.PROVIDE_VALID_EMAIL);
						return false;
					}
					return true;
				});
		});

	//Help Bubbles
	$('.bubble').live( 'hover' , function(e){
		$(this).find('.bubbleContent').toggle();
	});

	// Inputs hinting
	$('input[type=text].hinted')
		.bind('focus', function () {
			// Remove the hint on focus.
			if ($(this).val() == $(this).attr('sc:hint')) {
				$(this).val('');
			}
		})
		.bind('blur', function () {
			// Add the hint on blur.
			if (($(this).val() == '') && ($(this).attr('sc:hint') != '')) {
				$(this).val($(this).attr('sc:hint'));
			}
		})
		.each(function () {
			// Store the hint in the sc:hint attribute.
			$(this).attr('sc:hint', $(this).val());
			
			// Try to make sure the hint is not submitted as value.
			var hintedInput = $(this);
			$(this).parents('form:first') // find the form that the input is contained in
				.bind('submit', function () {
					if (hintedInput.val() == hintedInput.attr('sc:hint')) {
						hintedInput.val('');
					}
					return true;
				});
		});
	
	// IE6 flicker fix
	try {
		if ($.browser.msie && /6.0/.test(navigator.userAgent))
			document.execCommand("BackgroundImageCache", false, true);
	} catch (e) {}
});

// Language Dropdown Function
function languageDropdown(type)
{
	var languageOptions = document.getElementById("language-options");
	if (!languageOptions)
		return false;
	
	if (type == 'on')
		languageOptions.style.display = "block"; 
	else
		languageOptions.style.display = "none";
	
	return false;
}
