// Copyright (c) 2008 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 
};

SC.Home = new function()
{
	this.reloadTable = function(url, tableId)
	{
		$.post(
			url,
			{},
			function reloadTableSuccess(data) {
				// Set the html & eval the scripts
				$('#' + tableId).html(data);
				$("#loading").hide();
//				$('#' + tableId).html(data).evalScripts();
				SC.Home.setupFilterButtons();
			},
			'html'
		);
	}

	this.sortForm = function(formName, sortBy, sortDir, ajaxTable)
	{
		this.ajaxForm(formName, ajaxTable, 'sortDir=' + sortDir + '&sortBy=' + sortBy);
	}
	
	this.filterForm = function(formName, ajaxTable)
	{
		var form = $('#' + formName);
		var data = form.formSerialize();
		SC.Home.reloadTable(form.attr('action') + data, ajaxTable);
	}
	
	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++) {
			if (inputArray[i].name.slice(-6) == 'Filter')
				continue;
			if (inputArray[i].name.slice(-9) == 'Condition')
				continue;
			resultArray.push(inputArray[i]);
		}
		
		SC.Home.reloadTable(form.attr('action') + $.param(resultArray), ajaxTable);
	}
	
	this.ajaxForm = function(formName, ajaxTable, data)
	{
		var form = $('#' + formName);
		var data = data + '&' + form.formSerialize();
		SC.Home.reloadTable(form.attr('action') + data, ajaxTable);
	}
	
	this.setupAjax = function()
	{
		$(function() {
			$("#loading").ajaxStart(function() {
				$(this).show();
			});
			$("#loading").ajaxStop(function() {
				$(this).hide();
			});
		});
	}
	
	this.setupFilterButtons = function ()
	{
		$('.removeFiltersButton').click(function () {
			SC.Home.removeAllFiltersForm('table', 'entire_ajax_table');
		});
		$('.filterButton').click(function () {
			SC.Home.filterForm('table', 'entire_ajax_table');
		});
		$('.row').dblclick(function () {
			var href = $(this).find('a.onDblClick').attr('href');
			if (href)
				window.location.href = href;
		});
		$('select[@name=recordsPerPage]').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').submit(function() {
			SC.Home.filterForm('table', 'entire_ajax_table');
			return false;
		});
	}
	
	this.showErrors = function(errors)
	{
		for (var property in errors) {
			$('[@name=' + property + ']').add('#' + property).after('<div class="fieldError">^-- ' + errors[property] + '!</div>');
		}
	}
	
	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();
			});
			$('#' + i).mouseout(function() {
				$('#' + menus[this.id]).hide();
			});
		}
		
		$('#menu_store_link').add('#menu_website_content_link').
		add('#menu_reports_link').add('#menu_settings_link').add('#menu_modules_link').click(function() {
			return false;
		});
	}
};

SC.ML = new function()
{
	var LANG_SELECTED_CLASS = 'lang_selected';
	this.activeLanguages = [];
	this.currentLang = null;
	this.mlControlNames = [];
	
	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 in allLanguages) {
			SC.ML.activeLanguages.push(String(allLanguages[i]).match(re)[1]);
		}
		
		$('#dataLanguages>div>a[@href=#' + languageId + ']').click();
	}
	
	this.nextLanguage = function()
	{
		// 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.changeLanguage = function(languageId)
	{
		// Make the chosen language selected
		$('#dataLanguages>div>a').removeClass(LANG_SELECTED_CLASS);
		$('#dataLanguages>div>a[@href=#' + languageId + ']').addClass(LANG_SELECTED_CLASS);
		
		// 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 = 'none';
			}
		}
		
		// Show the new language
		for (var c in SC.ML.mlControlNames) {
			spanElem = document.getElementById('span' + c + '-' + languageId);
			if (spanElem)
				spanElem.style.display = '';
		}
		
		SC.ML.currentLang = languageId;
	}
	
	this.openWysiwygEditor = function(name, title)
	{
		var id = name + '[' + SC.ML.currentLang + ']';
		var url = 'popup/html_editor.php?id=' + id + '&TB_iframe=true&height=600&width=700';
		tb_show(title, url, false);
		$("#TB_overlay").unbind();
	}
	
	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);
		});
		
		$('#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 i=0; i<arr.length; i++) {
			if (arr[i] == str)
				return true;
		}
		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)
	{
		var url = '?load=table&action=dmPrint';
		if (moduleName)
			url = url + '&ModuleName=' + moduleName;
		
		// Open thickbox for printing
		tb_show('Print', url + '&TB_iframe=true', false);
		
		return false;
	}
	
	this.exportCSV = function(moduleName)
	{
		var data = $('#table').formSerialize();
		
		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;
		}
	}
}

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 = 30;
		this.arrowHeight = 50;
		
		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 in boxStrings) {
			var properties = boxStrings[i].split('=');
			if (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.");
	}
}

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

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