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

SC = new function()
{
	this.Home = {};
	this.Products = {};
	this.FeaturedProducts = {};
	this.Menu = {};
	this.Discounts = {};
	this.RS = {};	// Repeating Sections
	this.DMS = {};	// Double Multiple Select
	this.ML = {};	// Multilanguage
	this.Util = {};
	this.Boxes = {};// Admin CMS boxes 
	this.AjaxHistory = {};
};

SC.Home = new function()
{
	var categoryId = 0;
	
	this.reloadTable = function(url, tableId, postData)
	{
		// IE6 url starts with "?" fix
		if (url.charAt(0) == '?') {
			url = location.pathname + url;
		}
		
		$.post(
			url,
			postData,
			function reloadTableSuccess(data) {
				// Set the html & eval the scripts
				$('#' + tableId).html(data);
				$("#loading").hide();
//				$('#' + tableId).html(data).evalScripts();
				SC.Home.setupFilterButtons();
				SC.Home.setupFilterFields();
			},
			'html'
		);
	}
	
	this.sortForm = function(formName, sortBy, sortDir, ajaxTable)
	{
		this.ajaxForm(formName, ajaxTable, 'sortDir=' + sortDir + '&sortBy=' + sortBy);
	}
	
	this.filterForm = function(formName, ajaxTable)
	{
		var form = $('#' + formName);
		SC.Home.restoreFilterFields(formName);
		var data = form.formSerialize();
		SC.AjaxHistory.storeData(data);
		SC.Home.reloadTable(form.attr('action'), ajaxTable, data);
	}
	
	this.changeRecordsForm = function(formName, url, ajaxTable)
	{
		this.ajaxForm(formName, ajaxTable, url);
	}
	
	this.changePageForm = function(formName, url, ajaxTable)
	{
		this.ajaxForm(formName, ajaxTable, url);
	}
	
	this.removeAllFiltersForm = function(formName, ajaxTable)
	{
		var form = $('#' + formName);
		var inputArray = form.formToArray();
		
		// Build new inputs array skipping the Filter and Condition inputs
		var resultArray = [];
		for (i=0; i < inputArray.length; i++) {
			var name = inputArray[i].name;
			if (name.indexOf('[') >= 0)
				name = name.substr(0, name.indexOf('['));
			if (name.slice(-6) == 'Filter')
				continue;
			if (name.slice(-9) == 'Condition')
				continue;
			resultArray.push(inputArray[i]);
		}
		
		var data = $.param(resultArray);
		SC.AjaxHistory.storeData(data);
		SC.Home.reloadTable(form.attr('action'), ajaxTable, data);
	}
	
	this.ajaxForm = function(formName, ajaxTable, data)
	{
		var form = $('#' + formName);
		SC.Home.restoreFilterFields(formName);
		var data = data + '&' + form.formSerialize();
		SC.AjaxHistory.storeData(data);
		SC.Home.reloadTable(form.attr('action'), ajaxTable, data);
	}
	
	this.setupAjax = function()
	{
		$(function() {
			$("#loading").ajaxStart(function() {
				$(this).show();
			});
			$("#loading").ajaxStop(function() {
				$(this).hide();
			});
			if ($.historyInit) {
				$.historyInit(SC.AjaxHistory.callback);
			}
		});
	}
	
	this.setupFilterButtons = function ()
	{
		$('.removeFiltersButton').unbind('click').click(function () {
			SC.Home.removeAllFiltersForm('table', 'entire_ajax_table');
			return false;
		});
		$('.filterButton').unbind('click').click(function () {
			SC.Home.filterForm('table', 'entire_ajax_table');
			return false;
		});
		$('.row').unbind('dblclick').dblclick(function () {
			var href = $(this).find('a.onDblClick').attr('href');
			if (href)
				window.location.href = href;
		});
		$('select[name=recordsPerPage]').unbind('change').change(function () {
			var recordsPerPage = this.options[this.selectedIndex].value;
			
			// TODO: Temporary fix to work the records per page filter
			var params;
			if (this.form.elements.orderParams)
				params = this.form.elements.orderParams.value + '&';
			else
				params = '';
			
			SC.Home.changeRecordsForm('table', '?' + params + 'recordsPerPage=' + recordsPerPage , 'entire_ajax_table');
			
			// This is the original code
			// SC.Home.changeRecordsForm('table', this.form.elements.orderParams.value + '&recordsPerPage=' + recordsPerPage , 'entire_ajax_table');
		});
		
		// Allow filtering the form using the enter key
		$('#table').unbind('submit').submit(function() {
			SC.Home.filterForm('table', 'entire_ajax_table');
			return false;
		});
	}
	
	this.showErrors = function(errors)
	{
		var field, mlFieldName;
		
		var tooltipPrefix = '<div class="fieldError-tooltip" title="' + (typeof(ML_CLICK_TO_HIDE) != 'undefined' ? ML_CLICK_TO_HIDE : 'Click to hide') + '"><div>';
		var tooltipSuffix = '</div></div>';
		for (var property in errors) {
			// If the error is in multilanguage field, show all languages
			if (property.substr(property.length - 1) == ']') {
				mlFieldName = property.replace(/\[([0-9]+)\]$/, '');
				if (SC.Util.inArray(mlFieldName, SC.ML.mlControlNames)) {
					for (var i = 0; i < SC.ML.activeLanguages.length; i++) {
						spanElem = document.getElementById('span' + mlFieldName + '-' + SC.ML.activeLanguages[i]);
						if (spanElem)
							spanElem.style.display = '';
					}
				}
			}
			
			field = $('[name="' + property + '"]');
			if (field.length == 0) {
				field = $('#' + property);
			}
			field.addClass('error-field');
			
			var tabId = field.closest('div[id^=tab]').attr('id');
			$('[href=#' + tabId + ']').closest('li').addClass('tab-with-error')
			
			field.wrap('<div class="fieldError" />');
			field.after(tooltipPrefix + errors[property] + tooltipSuffix);
		}
		
		$('.fieldError-tooltip').click(function() { $(this).hide(); });
	}
	
	this.setupMenus = function()
	{
		var menus = Array();
		menus['menu_store_link'] = 'menu_store';
		menus['menu_store'] = 'menu_store';
		menus['menu_website_content_link'] = 'menu_website_content';
		menus['menu_website_content'] = 'menu_website_content';
		menus['menu_reports_link'] = 'menu_reports';
		menus['menu_reports'] = 'menu_reports';
		menus['menu_settings_link'] = 'menu_settings';
		menus['menu_settings'] = 'menu_settings';
		
		for (var i in menus) {
			$('#' + i).mouseover(function() {
				// Handle IE6 z-index problem
				if ($.fn.bgiframe != undefined)
					$('#' + menus[this.id]).bgiframe();
				
				$('#' + menus[this.id]).show();
				$('#' + menus[this.id] + '_link a').addClass('active-menu');
			});
			$('#' + i).mouseout(function() {
				$('#' + menus[this.id]).hide();
				$('#' + menus[this.id] + '_link a').removeClass('active-menu');
			});
		}
		
		$('#menu_store_link').add('#menu_website_content_link').
		add('#menu_reports_link').add('#menu_settings_link').add('#menu_modules_link').click(function() {
			return false;
		});
	}
	
	this.setupSearch = function()
	{
		var headerSearchInput = $('#search_textbox');
		if (!headerSearchInput.length)
			return;
		headerSearchInput.parents('form').submit(function () {
			$(this).children('input[type=text][sc:hint].inactive').attr('value', '').val('').attr('autocomplete', 'off');
		});
	}
	
	this.setupFilterFields = function()
	{
		var input = $(':input[sc:hint]');
		if (!input.length)
			return;
		
		if ($.browser.msie) {
			input.bind('focusin', function(){
				$(this).removeClass('inactive');
			});
		}
		input.focus(function(){
			var obj = $(this);
			if (obj.is('select')) {
				// It is a select. Check if it has the sc:defaultValue attribute
				if (!$.browser.msie) {
					obj.removeClass('inactive');
				}
			} else {
				// Not a select. Use the getFilterFieldHint() function.
				if ($(this).val() == SC.Util.getFilterFieldHint(this)) {
					$(this).removeClass('inactive').val("");
				}
			}
		}).blur(function(){
			var obj = $(this);
			if (obj.is('select')) {
				if (obj.is('select[sc\:defaultValue]') && (obj.val() == obj.attr('sc:defaultValue'))) {
					obj.addClass('inactive');
				}
			} else {
				if (obj.val() == "") {
					obj.addClass('inactive').val(SC.Util.getFilterFieldHint(this));
				}
			}
		}).trigger('blur');
	}
	
	this.restoreFilterFields = function(formName)
	{
		$('#' + formName + ' input[type=text][sc:hint].inactive').attr('value', '').val('').attr('autocomplete', 'off');
	}
};

SC.ML = new function()
{
	var LANG_SELECTED_CLASS = 'lang_selected';
	this.activeLanguages = [];
	this.currentLang = null;
	this.mlControlNames = [];
	this.allLanguagesOpened = false;
	
	this.registerMultilanguageControl = function(controlName)
	{
		this.mlControlNames[controlName] = controlName;
	}
	
	this.registerMultilanguageControls = function(controlNames)
	{
		for (var i = 0; i < controlNames.length; i++)
			this.registerMultilanguageControl(controlNames[i]);
	}
	
	this.unregisterMultilanguageControl = function(controlName)
	{
		delete this.mlControlNames[controlName];
	}
	
	this.unregisterMultilanguageControls = function(controlNames)
	{
		for (var j = 0; j < controlNames.length; j++)
			this.unregisterMultilanguageControl(controlNames[i]);
	}
	
	this.show = function()
	{
		$('#dataLanguages>div>a[href=#' + SC.ML.currentLang + ']').click();
	}
	
	this.initMultilanguageForm = function(formName, languageId)
	{
		$('#dataLanguages>div>a').click(function() {
			var languageId = this.href.split('#')[1];
			SC.ML.changeLanguage(languageId);
			return false;
		});
		
		// Find all active languages
		var allLanguages = $('#dataLanguages>div>a').get();
		var re = /#(\d+)$/;
		for(var i = 0, l = allLanguages.length; i < l; i++) {
			SC.ML.activeLanguages.push(String(allLanguages[i]).match(re)[1]);
		}
		
		$('#dataLanguages>div>a[href=#' + languageId + ']').click();
	}
	
	this.nextLanguage = function(selectedLanguageId)
	{
		if (SC.ML.allLanguagesOpened) {
			SC.ML.allLanguagesOpened = false;
			this.changeLanguage(selectedLanguageId);
			return;
		}
		
		// Get the next language
		for (var i = 0; i < SC.ML.activeLanguages.length; i++) {
			if (SC.ML.currentLang == SC.ML.activeLanguages[i])
				break;
		}
		
		// Change to the next language
		if (i + 1 == SC.ML.activeLanguages.length)
			this.changeLanguage(SC.ML.activeLanguages[0]);
		else
			this.changeLanguage(SC.ML.activeLanguages[i + 1]);
	}
	
	this.changeAllLanguages = function(displayProp)
	{
		for (var i = 0; i < SC.ML.activeLanguages.length; i++) {
			for (var c in SC.ML.mlControlNames) {
				spanElem = document.getElementById('span' + c + '-' + SC.ML.activeLanguages[i]);
				if (spanElem) {
					if (displayProp == 'none') {
						spanElem.style.display = 'block';
						spanElem.style.overflow = 'hidden';
						spanElem.style.height = '0';
					} else {
						spanElem.style.display = '';
						spanElem.style.overflow = '';
						spanElem.style.height = 'auto';
					}
				}
			}
		}
	}
	
	this.showAllLanguages = function()
	{
		SC.ML.allLanguagesOpened = true;
		$('.' + LANG_SELECTED_CLASS).removeClass(LANG_SELECTED_CLASS);
		$('.see-all-langs a').addClass(LANG_SELECTED_CLASS);
		this.changeAllLanguages('');
	}
	
	this.changeLanguage = function(languageId)
	{
		// Make the chosen language selected
		$('#dataLanguages>div>a').removeClass(LANG_SELECTED_CLASS);
		$('#dataLanguages>div>a[href=#' + languageId + ']').addClass(LANG_SELECTED_CLASS);
		
		this.changeAllLanguages('none');
		
		// Hide the current language
		if (SC.ML.currentLang != null) {
			for (var c in SC.ML.mlControlNames) {
				spanElem = document.getElementById('span' + c + '-' + SC.ML.currentLang);
				if (spanElem) {
					spanElem.style.display = 'block';
					spanElem.style.overflow = 'hidden';
					spanElem.style.height = '0';
				}
			}
		}
		
		// Show the new language
		for (var c in SC.ML.mlControlNames) {
			spanElem = document.getElementById('span' + c + '-' + languageId);
			if (spanElem) {
				spanElem.style.display = '';
				spanElem.style.overflow = '';
				spanElem.style.height = 'auto';
			}
		}
		
		SC.ML.currentLang = languageId;
	}
	
	this.setupWysiwygEditors = function(name, language, contentCss)
	{
		CKEDITOR.config.language = language;
		for (var i = 0; i < SC.ML.activeLanguages.length; i++) {
			var id = name + '[' + SC.ML.activeLanguages[i] + ']';
			if (SC.ML.currentLang != SC.ML.activeLanguages[i]) {
				setTimeout('SC.ML.setupWysiwygEditor(\'' + id + '\', 200, \'' + contentCss + '\');', 1000)
			} else {
				SC.ML.setupWysiwygEditor(id, 200, contentCss);
			}
		}
	}
	
	this.setupWysiwygEditor = function(id, height, contentCss)
	{
		var params = {
			'height': height,
			'contentsCss': contentCss
		};
		if (!$.browser.safari)
			params['width'] = '100%';
		CKEDITOR.replace(id, params);
	}
	
	this.removeWysiwygEditors = function(name)
	{
		for (var i = 0; i < SC.ML.activeLanguages.length; i++) {
			var id = name + '[' + SC.ML.activeLanguages[i] + ']';
			if (CKEDITOR.instances[id])
				CKEDITOR.instances[id].destroy();
		}
	}
	
	this.initMultilanguageTable = function(formName, ajaxTable, languageId)
	{
		$('#dataLanguages>div>a').click(function() {
			var languageId = this.href.split('#')[1];
			$('input[name=DataLanguage]').val(languageId);
			SC.Home.filterForm(formName, ajaxTable);
			
			// Make the chosen language selected
			$('#dataLanguages>div>a').removeClass(LANG_SELECTED_CLASS);
			$('#dataLanguages>div>a[href=#' + languageId + ']').addClass(LANG_SELECTED_CLASS);
			return false;
		});
		
		$('#dataLanguages>div>a[href=#' + languageId + ']').addClass(LANG_SELECTED_CLASS);
	}
}

SC.Util = new function()
{
	this.updateCheckedCount = function(checkboxes, countElem)
	{
		var count = 0;
		checkboxes.each(function() {
			if (this.checked)
				count++;
		});
		
		countElem.html(String(count));
	}
	
	/**
	 * Returns a string with the object properties
	 *
	 * @param object obj
	 * @param string objectName
	 */
	this.objToString = function(obj, objectName) {
		var result = "";
		for (var i in obj) {
			if (typeof(i) == "object") {
				result += showProps(i, objectName + '[i]');
			} else {
				result += objectName + "." + i + " = " + obj[i] + "\n";
			}
		}
		return result;
	}
	
	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.arraySearch = function(str, arr) {
		for (var key in arr) {
			if (typeof(arr[key]) == 'function') {
				continue;
			}
			if (arr[key] == str) {
				return key;
			}
		}
		return false;
	}
	
	this.setDatePicker = function(options)
	{
		if (options == undefined)
			options = {};
		options.displayClose = true;
		options.startDate = '01/01/2005';
		$('input.date-pick').datePicker(options).each(function(obj) {
			if (this.value != '')
				$(this).change();
		});
	}

	this.print = function(moduleName, formName)
	{
		var url = '?load=table&action=dmPrint';
		if (moduleName)
			url = url + '&ModuleName=' + moduleName;
		if (formName) {
			SC.Home.restoreFilterFields('table');
			url = url + '&' + $('#' + formName).formSerialize();
			SC.Home.setupFilterFields();
		}
		
		// Open lightbox for printing
		$.colorbox({href: url, title: 'Print', iframe: true, width: 600, height: 450});
		
		return false;
	}
	
	this.exportCSV = function(moduleName)
	{
		SC.Home.restoreFilterFields('table');
		var data = $('#table').formSerialize();
		SC.Home.setupFilterFields();
		
		var url = '?action=dmExport&' + data;
		if (moduleName)
			url = url + '&ModuleName=' + moduleName;
		window.location.href = url;
	}
	
	this.filterStates = function(selectControl, selectedStateId, countryId, statesArray)
	{
		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.toggleAdditionalFilters = function(checkbox, shownElementSelector)
	{
		if ($(checkbox).attr('checked') == true) {
			if ($.browser.msie && $.browser.version.substr(0,1) <= 7) {
				$(shownElementSelector).css('display', 'block');
			} else {
				$(shownElementSelector).css('display', 'table-row');
			}
		} else {
			$(shownElementSelector).css('display', 'none');
		}
	}
	
	this.getFilterFieldHint = function(obj)
	{
		if ($(obj).attr('sc:hint')) {
			return $(obj).attr('sc:hint');
		}
		return '';
	}
}

SC.Boxes = new function()
{
	// Public
	this.init = function(arrowLeft, arrowRight, boxes, fadeTime)
	{		
		// Initialize the arrow urls
		this.arrowLeft = arrowLeft;
		this.arrowRight = arrowRight;
		
		// Get the boxes description
		this.boxes = boxes;
		
		// Restore the boxes state
		this.restoreState();
		
		// Setup sizes
		this.boxesWidth = 195;
		this.arrowWidth = 37;
		this.arrowHeight = 34;
		
		for (var i in this.boxes) {
			this.boxes[i]['height'] = $('#' + i).height();
			
			if (this.boxes[i]['visible'] == 0)
				$('#' + i).width(this.arrowWidth).height(this.arrowHeight);
		}
		
		// Set the transition fade time
		this.fadeTime = !fadeTime ? 1500 : fadeTime;
	}
	
	this.toggleBox = function(boxId)
	{
		var box = this.boxes[boxId];
		if (box['visible'] == 0) {
			this.showBox(box);
			box['visible'] = 1;
		} else {
			this.hideBox(box);
			box['visible'] = 0;
		}
		
		this.saveState();
	}
	
	// Protected
	this.saveState = function()
	{
		$.cookie('SCBoxes', this.serializeBoxes());
	}
	
	this.restoreState = function()
	{
		var cookie = $.cookie('SCBoxes');
		if (cookie)
			this.unserializeBoxes(cookie);
	}
	
	this.serializeBoxes = function()
	{
		var result = '';
		for (var i in this.boxes)
			result += i + '=' + this.boxes[i]['visible'] + '|';
		
		return result.slice(0, result.length - 1);
	}
	
	this.unserializeBoxes = function(serializedBoxes)
	{
		var boxStrings = serializedBoxes.split('|');
		for (var i=0; i < boxStrings.length; i++) {
			var properties = boxStrings[i].split('=');
			if ((properties.length == 2) && this.boxes[properties[0]])
				this.boxes[properties[0]]['visible'] = properties[1];
		}
	}
	
	this.showBox = function(box)
	{
		var element = box['id'];
		$('#' + element + '_arrow_closed').css("display", "none");
		$('#' + element).css("display", "block");
		$('#' + element).animate({width: this.boxesWidth, height: box['height']}, SC.Boxes.fadeTime);
	}
	
	this.hideBox = function(box)
	{
		var element = box['id'];
		$('#' + element).animate({width: this.arrowWidth, height: this.arrowHeight}, SC.Boxes.fadeTime, "swing", function() {
			$('#' + element).css("display", "none");
			$('#' + element + '_arrow_closed').css("display", "block");
		});
	}
}

SC.Debug = new function()
{
	this.dump = function(object)
	{
		var result = '';
		for (var property in object)
			result += property + ':' + object[property] + "\n";

		alert(result);
	}
	
	this.benchmark = function(what, times)
	{
		if (!times)
			times = 10;
		
		var start = (new Date).getTime();
		for (var i=0; i < times; i++) {
			eval(what);
		}
		var end = (new Date).getTime();
		alert("Took " + ((end - start) / times) + " ms.");
	}
}

SC.AjaxHistory = new function()
{
	this.lastLoadedParams = '';
	
	this.callback = function(params)
	{
		// Check if the same url was visited twice.
		if (params == SC.AjaxHistory.lastLoadedParams) {
			return;
		}
		// If loading the clean URL (orders.php) without any parameters, add load=table
		if (params == '') {
			params = 'load=table&' + location.search.replace(/^\?/, '');
		}
		
		var formId = 'table';	// FIXME
		var ajaxTable = 'entire_ajax_table';
		
		SC.AjaxHistory.lastLoadedParams = location.hash.replace(/^#/, '');
		SC.Home.reloadTable($('#' + formId).attr('action'), ajaxTable, params);
	}
	
	this.storeData = function(params)
	{
		params = params.replace(/^(#*)\?/, '$1');
		if (params == 'load=table') {
			SC.AjaxHistory.lastLoadedParams = '';
			return;
		}
		try {
			location.hash = params;
		} catch (exception) {
			// IE says "Access denied" on too long query strings. Ignore it.
			// Side effect: jquery history does not work.
			// Mat happens in "Language texts".
		}
		// Store loaded params
		SC.AjaxHistory.lastLoadedParams = location.hash.replace(/^#/, '');
	}
}

/**
 * Page setup
 */
SC.Home.setupAjax();

$(function() {
	$('#UILanguage').change(function() {
		var url = window.location.search;
		if (url.indexOf('?') == -1)
			url += '?';
		window.location.search = url.replace(/&UILanguage=../g, '') + '&UILanguage=' + this.value;
	});
	
	SC.Home.setupMenus();
	SC.Home.setupSearch();
	SC.Home.setupFilterButtons();
	SC.Home.setupFilterFields();
	
	$('#exportCSV').click(SC.Util.exportCSV);
});
