/**
 * Design step handler
 *
 * @copyright (c) 2004-2006, SWsoft
 */
function SB_Design(templatesUrl) {
	this._url				= templatesUrl;
	this._code				= null;
	this._icon				= null;
	this._category			= null;
	this._keywords			= null;
	this._logo				= null;
	this._customLogo		= null;
	this._headerKeys		= new Array();
	this._headers			= new Array();
	this._headerIndex		= 0;
	this._customHeaders		= new Array();
	this._colorSchemes 		= new Array();
	this._colorSchemeIndex	= 0;
	this._buttons			= new Array();
	this._buttonIndex		= null;

	this._savedHeaders		= new Array();
	
	this._previousTemplate	= null;
}

SB_Design.prototype.goToPage = function(page) {
	this._setViewParam('page', page);
	this._setViewParam('category', document.getElementById('category').value);
	this._setViewParam('search', document.getElementById('search').value, true);
	sbNavigationObject.go();
}

SB_Design.prototype.changeTemplatesPerPage = function(templatesPerPage) {
	this._setViewParam('page', 1);
	this._setViewParam('templatesPerPage', templatesPerPage);
	this._setViewParam('category', document.getElementById('category').value);
	this._setViewParam('search', document.getElementById('search').value, true);
	sbNavigationObject.go();
}

SB_Design.prototype.getBestFitTemplatesNumber = function() {
	var cellHeight = 140;
	var cellWidth = 140;
	
	var divHeight = $('outerTemplateListContainer').getHeight();
	var divWidth = $('outerTemplateListContainer').getWidth();
	
	rows = Math.floor(divHeight / cellHeight);
	cols = Math.floor(divWidth / cellWidth);
		
	return ((rows * cols) - 4);
}

SB_Design.prototype.validateAndGoToPage = function(page, pageCount) {
	if(validateField('SB_Validator.isDigits', 'goToPage', 'INCORRECT-PAGE-NUMBER')
		&& extendedValidateField("SB_Validator.isBetween("+page+", 1, "+pageCount+")", 'goToPage', 'MAX-PAGE-NUMBER')
	) {
		this._setViewParam('page', page);
		this._setViewParam('category', document.getElementById('category').value);
		this._setViewParam('search', document.getElementById('search').value, true);
		sbNavigationObject.go();
	}
}

SB_Design.prototype.prepareGoToPageInput = function(pageCount, event) {
	var designControl = this;
	var goToPageInput = document.getElementById('goToPage');
	goToPageInput.onkeypress = function (event) {designControl.onGotoPageKeypress(event, pageCount);};
}

SB_Design.prototype.onGotoPageKeypress = function(event, pageCount) {
	if (document.all) event = self.event;
	if (event.keyCode == 13) {
		stopEvent(event);
		this.validateAndGoToPage(document.getElementById('goToPage').value, pageCount);
		return false;
	}
	return true;
}

SB_Design.prototype.searchCategory = function(category) {
	this._setViewParam('category', category);
	this._setViewParam('page', 1);
	this._setViewParam('search', document.getElementById('search').value, true);
	sbNavigationObject.go();
}

SB_Design.prototype.prepareSearchInput = function(event) {
	var designControl = this;
	var searchInput = document.getElementById('search');
	searchInput.onkeypress = function (event) {designControl.onSearchKeypress(event);};
}

SB_Design.prototype.onSearchKeypress = function(event) {
	if (document.all) event = self.event;
	if (event.keyCode == 13) {
		stopEvent(event);
		var searchInput = document.getElementById('search');
		this.searchSubstring(searchInput.value);
		return false;
	}
	return true;
}

SB_Design.prototype.searchSubstring = function(substring) {
	this._setViewParam('category', document.getElementById('category').value);
	this._setViewParam('search', substring, true);
	sbNavigationObject.go();
}

SB_Design.prototype.showAllTemplates = function() {
	this._setViewParam('category', -1);
	this._setViewParam('search', '', true);
	sbNavigationObject.go();
}

SB_Design.prototype.selectTemplate = function(code
											, colorScheme
											, colorSchemes
											, icon
											, logo
											, header
											, headers
											, button
											, buttons
											, category
											, keywords
											, customHeaders
											, isHeaderUploadSupport
											, customLogo) {

	this.updateHeaderUploadControls(isHeaderUploadSupport);
	
	this._code			= code;
	this._icon			= icon;
	this._category		= category;
	this._keywords		= keywords;
	this._logo			= logo;
	this._colorSchemes	= colorSchemes.split("|");
	this._colorSchemeIndex = this._getIndex(colorScheme, this._colorSchemes); //#97722
	this._buttons		= buttons.split("|");
	this._buttonIndex	= this._getIndex(button, this._buttons); //#97722

	this._savedHeaders  = headers;
	this._customHeaders = customHeaders;
	this._initHeaders();
	

	this._headerIndex	= this._getIndex(header, this._headerKeys); //#97722
	this._customLogo	= customLogo != '' ? customLogoUrl + '/' + customLogo : '';
	
	if(this._previousTemplate) {
		element = document.getElementById('template_' + this._previousTemplate);
		if(element) {
			element.style.border = "1px solid rgb(204, 204, 204)";
		}
	}
	
	element = document.getElementById('template_' + code);
	if(element) {
		element.style.border = "1px solid rgb(255, 61, 12)";
		this._previousTemplate = code;
	}


	this.updatePreview();
	this.save();

}

SB_Design.prototype.selectNewTemplate = function(code
												, colorScheme
												, colorSchemes
												, icon
												, logo
												, headers
												, buttons
												, category
												, keywords
												, customHeaders
												, isHeaderUploadSupport
												, customLogo) {

	this.updateHeaderUploadControls(isHeaderUploadSupport);
	
	var isCustomHeaderSelected = (this._headerIndex+1 > this._savedHeaders.split("|").length);
													
	this._code			= code;
	this._icon			= icon;
	this._category		= category;
	this._keywords		= keywords;
	this._logo			= logo;
	this._colorSchemes	= colorSchemes.split("|");
	this._colorSchemeIndex = this._getIndex(colorScheme, this._colorSchemes);
	this._buttons		= buttons.split("|");
	this._buttonIndex	= 0; //this._getIndex(button, this._buttons); #97722

	this._savedHeaders  = headers;
	this._customHeaders = customHeaders;
	this._initHeaders();

	if (isCustomHeaderSelected) {
		// custom header have index greater by one than total of original headers
		this._headerIndex = this._savedHeaders.split("|").length;
	} else {
		this._headerIndex = 0;
	}
	
	if ('' != customLogo
		&& "no" == document.getElementById("isLogoReseted").value 
		&& "no" == document.getElementById("isLogoDeleted").value
	) {
		this._customLogo =  customLogoUrl + '/' + customLogo;
	} else {
		this._customLogo	= null;
	}

	this.updatePreview();
	this.save();

	if(this._previousTemplate) {
		element = document.getElementById('template_' + this._previousTemplate);
		if(element) {
			element.style.border = "1px solid rgb(204, 204, 204)";
		}
	}
	
	element = document.getElementById('template_' + code);
	if(element) {
		element.style.border = "1px solid rgb(255, 61, 12)";
		this._previousTemplate = code;
	}
	
}

SB_Design.prototype._initHeaders = function() {
	this._headerKeys = this._savedHeaders.split("|");

	if ('' == this._headerKeys) {
		$('headerSelectionCombobox').onclick = null;
		$('headerSelectionCombobox').setStyle({filter: 'gray alpha(opacity=40)', '-moz-opacity': 0.4, opacity: 0.4, cursor: 'default'});
	} else {
		$('headerSelectionCombobox').onclick = function(event) { sb_design.showHeadersList($('headersList')); };
		$('headerSelectionCombobox').setStyle({filter: '', '-moz-opacity': 1, opacity: 1, cursor: 'pointer'});
	}
	
	this._headers = new Array();
	for (var i = 0; i < this._headerKeys.length; i++) {
		this._headers[i] = this._url + "/" + this._code + "/" + this._getColorScheme() + "/headers/" + this._headerKeys[i] + '.jpg';
	}

	var tmp = this._headerKeys.length;
	for (var j = 0; j < this._customHeaders.length; j++) {
		this._headerKeys[tmp + j] = this._customHeaders[j];
		this._headers[tmp + j] = customHeaderUrl + '/' + this._customHeaders[j];
	}
}

SB_Design.prototype.selectButton = function(index) {
	this._buttonIndex = index;
	this._writeButtons();
	this.save();
}

SB_Design.prototype.selectColorScheme = function(index) {
	this._colorSchemeIndex = index;
	this._initHeaders();
	this.updatePreview();
	this.save();
}

SB_Design.prototype.selectHeader = function(index) {
	this._headerIndex = index;
	this._writeHeader(this._headerIndex);
	this.save();
}

SB_Design.prototype.showHeadersList = function(control) {
	var item = document.getElementById(control.id + '_popup');
	var hidden = document.getElementById(control.id + '_hidden');
	if (hidden.value == "false") {
		this._writeHeadersPopup();
		item.style.display = 'block';
		hidden.value = "true";
	} else {
		item.style.display = 'none';
		hidden.value = "false";
	}
}

SB_Design.prototype.save = function() {
	var result1 = this._saveField("activeTemplate", this._code);
	var result2 = this._saveField("activeColorScheme", this._colorSchemes[this._colorSchemeIndex]);
	var result3 = this._saveField("activeHeader", this._headerKeys[this._headerIndex]);
	var result4 = this._saveField("activeButton", this._buttons[this._buttonIndex]);

	if (result1 || result2 || result3 || result4) {
		self.sbApplyChangesObject.registerChange();
		self.sbApplyChangesObject.registerForcedSaving();
	}
}

SB_Design.prototype.updatePreview = function() {
	document.getElementById("smallPreview").src
		= this._url + "/" + this._code + "/" + this._getColorScheme() + "/" + this._icon;
	document.getElementById("labelIdContent").innerHTML = this._code;
	document.getElementById("labelCategoryContent").innerHTML = this._category;
	document.getElementById("labelKeywordsContent").innerHTML = this._keywords;
	this._writeColorSchemes();
	this._writeHeader(this._headerIndex);
	this._writeButtons();
	this._writeLogo();
	this._writeHeadersPopup();
}

SB_Design.prototype.setDefaultLogo = function() {
	this._customLogo = null;
	document.getElementById("isLogoReseted").value = 'yes';
	document.getElementById("isLogoDeleted").value = 'no';
	document.getElementById("templateLogo").innerHTML = this._getLogoHtml();
	self.sbApplyChangesObject.registerChange();
	self.sbApplyChangesObject.registerForcedSaving();
}

SB_Design.prototype.setEmptyLogo = function() {
	this._customLogo = null;
	document.getElementById("templateLogo").innerHTML = '';
	document.getElementById("isLogoReseted").value = 'no';
	document.getElementById("isLogoDeleted").value = 'yes';
	self.sbApplyChangesObject.registerChange();
	self.sbApplyChangesObject.registerForcedSaving();
}

SB_Design.prototype._getHeader = function(index) {
	return this._headers[typeof(index)!='undefined' ? index : this._headerIndex];
}

SB_Design.prototype._getButton = function(index) {
	return this._buttons[typeof(index)!='undefined' ? index : this._buttonIndex]+'.jpg';
}

SB_Design.prototype._getColorScheme = function(index, ee) {
	return this._colorSchemes[typeof(index)!='undefined' ? index : this._colorSchemeIndex];
}

SB_Design.prototype._writeHeader = function(index) {
	var headerHtml = this._getHeaderHtml(index);
	
	if (Sb.isPageLoaded) {	
		document.getElementById("selectedHeader").innerHTML = headerHtml;
	} else {		
		RegisterOnloadAction("document.getElementById(\"selectedHeader\").innerHTML = '" + headerHtml + "'");
	}
}

SB_Design.prototype._writeHeadersPopup = function() {
	document.getElementById("headersList_popup").innerHTML
		= this._getHeadersPopupHtml();
}

SB_Design.prototype._writeColorSchemes = function() {
	$('colorSchemesList').update(this._getColorSchemesListHtml());
}

SB_Design.prototype._writeButtons = function() {
	document.getElementById("buttonsList").innerHTML = this._getButtonsListHtml();
}

SB_Design.prototype._writeLogo = function() {
	var logoHtml = this._getLogoHtml();
	
	if (Sb.isPageLoaded) {	
		document.getElementById("templateLogo").innerHTML = logoHtml;
	} else {		
		RegisterOnloadAction("document.getElementById(\"templateLogo\").innerHTML = '" + logoHtml + "'");
	}
}

SB_Design.prototype._getLogoHtml = function() {
	var html = '';
	
	if (this._customLogo && this._customLogo.length > 1) {
		html = '<img src="' + this._customLogo + '" style="display: none; border-width: 0px;" onload="sb_design.resizeLogo(this); $(this).show();">';
	} else if (document.getElementById("isLogoDeleted").value!='yes') {
		html = '<img src="' + this._url + "/" + this._code + "/" + this._getColorScheme() + "/images/" + this._logo + '" style="display: none; border-width: 0px;" onload="sb_design.resizeLogo(this); $(this).show();">';
	}
	
	return html;
}

SB_Design.prototype._getHeaderHtml = function(index) {
	return '<img src="' + this._getHeader(index) + '" style="display: none; border-width: 0px;" alt="" onload="sb_design.resizeHeader(this); $(this).show();"/>';
}

SB_Design.prototype.resizeHeader = function(element) {
	this.resizeImage(element, 230, 56);
}

SB_Design.prototype.resizeLogo = function(element) {
	this.resizeImage(element, 53, 53);
}

SB_Design.prototype.resizeImage = function(element, maxWidth, maxHeight) {
	Sb.Console.log('Call : SB_Design.prototype.resizeImage');
	
	element = $(element);
	var dimensions = element.getDimensions();
	
	Sb.Console.log('Image : original width : ' + dimensions.width);
	Sb.Console.log('Image : original height : ' + dimensions.height);
	
	if ((0 == dimensions.width) || (0 == dimensions.height)) {
		return ;
	}
	
	wRatio = maxWidth / dimensions.width;
	hRatio = maxHeight  / dimensions.height;
	ratio = (wRatio < hRatio) ? wRatio : hRatio;
 
	element.setStyle({
		width: Math.round(dimensions.width * ratio) + 'px',
		height: Math.round(dimensions.height * ratio) + 'px'
	});
	
	Sb.Console.log('Image : ratio : ' + ratio);
	Sb.Console.log('Image : new width : ' + element.getWidth());
	Sb.Console.log('Image : new height : ' + element.getHeight());
}

SB_Design.prototype._getHeadersPopupHtml = function() {
	var fullUrl = this._url + "/" + this._code + "/" + this._getColorScheme() + "/headers/";
	var str = '';
	for (var i = 0; i < this._headers.length; i++) {
		var style = 'background-color: white; width: 100%;';
		if (i == this._headerIndex) {
			style += 'border-color: red; border-width: 2px; border-style: solid;';
		}
		str += '<table onclick="sb_design.selectHeader(' + i + ');return false;" cellspacing="0" cellpadding="0" border="0" style="width: 100%; border-collapse: collapse; cursor: pointer;"> '
			+	'<tr>'
			+		'<td align="center" valign="middle" style="' + style + '">'
			+			this._getHeaderHtml(i)
			+		'</td>'
			+	'</tr>'
			+	'</table>';
	}
	return str;
}

SB_Design.prototype._getColorSchemesListHtml = function() {
	if (this._colorSchemes.length > 3) {
		return this._getColorSchemesDropDownListHtml();
	} else {
		return this._getColorSchemesSimpleListHtml();
	}
}	

SB_Design.prototype._getColorSchemesDropDownListHtml = function() {
	var str = '';
		
	str += '<table cellpadding="0" cellspacing="0" border="0" style="border: 1px solid #9B9B9B; width: 249px; margin: 3px 10px 0px" id="colorSchemesDropDown">';
	str += '<tr><td>';
	str += '<table cellspacing="0" cellpadding="0" border="0" style="width: 100%; border-collapse: collapse; background-color: #FFFFFF;">';
	str += '<tr>';
	
	str += '<td>';
	
	var itemsPerRow = 3;
	var startIndex = (Math.ceil((this._colorSchemeIndex+1) / itemsPerRow) - 1) * itemsPerRow;
	
	for (var i = startIndex; i < (startIndex + itemsPerRow); i++) {
		str += this._getColorSchemeItemHtml(i);
	}
		
	str += '</td>';
	
	str += '<td style="width: 19px; cursor: pointer; vertical-align: bottom" onclick="sb_design.toggleColorSchemePopup();">';
	str += '<img src="' + sbSkinPath + '/images/DropDownMiddle.gif" style="border-width:0px;">';
	
	str += '</td>';
	
	str += '</tr>';
	str += '</table>';
	str += '</td></tr>';
	str += '</table>';

	// prepare popup
	str += '<div id="colorSchemesListPopup" style="display: none; overflow: auto; position: absolute; z-index: 1; border: 1px solid #9B9B9B; background-color: #FFFFFF; width: 249px; margin-left: 10px;">';
		
	for (var i = 0; i < this._colorSchemes.length; i++) {
		str += this._getColorSchemeItemHtml(i);
	}
	
	str += '</div>';
	
	return str;
}

SB_Design.prototype._getColorSchemeItemHtml = function(schemeIndex) {
	var styleClass = (this._colorSchemeIndex == schemeIndex)
		? 'sb-wizard-content-settings-schemes-thumbnails-active'
		: 'sb-wizard-content-settings-schemes-thumbnails-normal';

	var colorSchemeName = this._getColorScheme(schemeIndex);
	var src = this._url + "/" + this._code + "/" + colorSchemeName + "/" + this._icon;
	
	if ((schemeIndex+1) > this._colorSchemes.length) {
		return '<span style="float: left; padding-left: 3px; padding-top: 3px; padding-bottom: 3px;"><img src="/images/blank.gif" width="72" height="72"/></span>';
	} else {	
		return '<span style="float: left; padding-left: 3px; padding-top: 3px; padding-bottom: 3px;">'
			+		'<table cellpadding="0" cellspacing="0" border="0" class="' + styleClass + '" onclick="sb_design.selectColorScheme(' + schemeIndex + ');return false;">'
			+			'<tr>'
			+				'<td class="sb-wizard-content-settings-schemes-thumbnails-inner">'
			+					'<img width="58" height="53" border="0" alt="' + colorSchemeName + '" src="' + src + '"/>'
			+				'</td>'
			+			'</tr>'
			+		'</table>'
			+ 	'</span>';
	}
}

SB_Design.prototype.toggleColorSchemePopup = function() {
	$('colorSchemesListPopup').toggle();
}

SB_Design.prototype._getColorSchemesSimpleListHtml = function() {
	var str = '<table cellpadding="0" cellspacing="0" border="0" class="sb-wizard-content-settings-schemes"><tr><td class="sb-wizard-content-settings-schemes-thumbnails"><table cellpadding="0" cellspacing="0" border="0" class="sb-wizard-content-settings-schemes-thumbnails-block"><tr>';
	var klass = '';
	var fullUrl = this._url + "/" + this._code + "/";
	for (var i = 0; i < this._colorSchemes.length; i++) {
		var align = 'left';
		
		if (i == this._colorSchemeIndex) {
			klass = "sb-wizard-content-settings-schemes-thumbnails-active";
		} else {
			klass = "sb-wizard-content-settings-schemes-thumbnails-normal";
		}
		
		var colorSchemeName = this._getColorScheme(i);
		
		var src = fullUrl + colorSchemeName + "/" + this._icon;
		
		str	+=	'<td align="'+ align + '" class="sb-wizard-content-settings-schemes-thumbnail">' 
			+		'<table cellpadding="0" cellspacing="0" border="0" class="' + klass + '" onclick="sb_design.selectColorScheme(' + i + ');return false;">'
			+			'<tr>'
			+				'<td class="sb-wizard-content-settings-schemes-thumbnails-inner">'
			+					'<img width="58" height="53" border="0" alt="' + colorSchemeName + '" src="' + src + '"/>'
			+				'</td>'
			+			'</tr>'
			+		'</table>'
			+	'</td>';
	}
	str += "</tr></table></td></tr></table>";
	return str;
}

SB_Design.prototype._getButtonsListHtml = function() {
	var str = '<table cellpadding="0" cellspacing="0" border="0" class="sb-wizard-content-settings-menus"><tr><td class="sb-wizard-content-settings-menus-thumbnails"><table cellpadding="0" cellspacing="0" border="0" class="sb-wizard-content-settings-menus-thumbnails-block"><tr>';
	var fullUrl = this._url + "/" + this._code + "/" + this._getColorScheme() + "/buttons/";
	for (var i = 0; i < this._buttons.length; i++) {
		var align = 'left';		
		var klass = '';
		if (i == this._buttonIndex) {
			klass = "sb-wizard-content-settings-menus-thumbnails-active";
		} else {
			klass = "sb-wizard-content-settings-menus-thumbnails-normal";
		}

		var src = fullUrl + this._getButton(i);
		str +=	'<td align="'+ align + '" class="sb-wizard-content-settings-menus-thumbnail">'
			+	'<table cellpadding="0" cellspacing="0" border="0" class="' + klass + '" onclick="sb_design.selectButton(' + i + ');return false;">'
			+		'<tr>'
			+			'<td class="sb-wizard-content-settings-menus-thumbnails-active-inner">'
			+				'<img src="' + src + '" alt="" width="69" height="26"/></td>'
			+		'</tr>'
			+	'</table>'
			+	'</td>';
	}
	str += "</td></tr></table>";
	return str;
}

SB_Design.prototype._getIndex = function(val, collection) {
	var result = 0;
	for (result = 0; result < collection.length; ++result) {
		if (val==collection[result]) {
			break;
		}
	}	
	return result;
}

SB_Design.prototype._saveField = function(controlId, val) {
	var control = document.getElementById(controlId);
	var isChanged = control.value!='' && control.value!=val;
	control.value = val;
	return isChanged;
}

SB_Design.prototype._setViewParam = function(field, val, force) {
	if (typeof(force)=='undefined') {
		force = false;
	}
	if (field || val!='') {
		sbNavigationObject.setViewParam(field, val);
	}
}
SB_Design.prototype.previewBigIcon = function() {
	var width = 808;
	var height = 712;
	var bigIcon = this._url + "/" + this._code + "/" + this._getColorScheme() + "/" + 'icon_big.gif';
	var itemPreview = window.open('', 'previewItem', 'width=' + width + ',height=' + height + ', statusbar=no,toolbar=no,scrollbars=yes');
	itemPreview.document.open();
//	itemPreview.document.write('<html><head></head><body style="margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; background-color: white;"><img src="'+bigIcon+'" width="' + width + '" height="' + height + '" alt="" border="0" align="center"></body>');
	itemPreview.document.write('<html><head></head><body style="margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; background-color: white;"><img src="'+bigIcon+'"  alt="" border="0" align="center"></body>');
	itemPreview.document.close();
	try {
		itemPreview.resizeTo(width, height);
		itemPreview.focus();
	} catch(e) {};

	return false;
}

SB_Design.prototype.submitHeaderUploadForm = function(field) {
	if (validateField('SB_Validator.notEmpty', field, 'EMPTY-UPLOAD-FILE')) {
		document.forms['SB_WizardForm'].submit();
		return true;
	} else {
		return false;
	}
}

SB_Design.prototype.submitLogoUploadForm = function(field) {
	if (validateField('SB_Validator.notEmpty', field, 'EMPTY-UPLOAD-FILE')) {
		document.getElementById("isLogoReseted").value = 'no';
		document.getElementById("isLogoDeleted").value = 'no';
		document.forms['SB_WizardForm'].submit();
		return true;
	} else {
		return false;
	}
}

SB_Design.prototype.updateHeaderUploadControls = function(isHeaderUploadSupport) {
	if (isHeaderUploadSupport) {
		$('customHeader').disabled = '';
		$('headerUploadButton').onclick = function(event) { sb_design.submitHeaderUploadForm('customHeader'); };
		$('headerUploadButton').setStyle({filter: '', '-moz-opacity': 1, opacity: 1, cursor: 'pointer'});
		$('headerUploadButtonMainText').removeClassName('sb-login-control-button-disabled');
	} else {
		$('customHeader').disabled = 'disabled';
		$('headerUploadButton').onclick = null;
		$('headerUploadButton').setStyle({filter: 'gray alpha(opacity=40)', '-moz-opacity': 0.4, opacity: 0.4, cursor: 'default'});
		$('headerUploadButtonMainText').addClassName('sb-login-control-button-disabled');
	}
}

function validateForm() {
	return true;
}