/**
 * @author Administrator
 */

/* country selector
----------------------------------------------------- */
var LanguageList = Class.create(Menu, {
	selectMenu: function($super, oMenuItem) {
		$super(oMenuItem);
		var country = oMenuItem.id;
		new Ajax.Request('langCallNewsletter.php?action=selectCountryAction&country=' + country, {
			method: 'get',
			onComplete: function(resp) {
				if(resp.responseText === '1') {
                                        var url = window.location.href;
                                        var pos = url.indexOf('country');
                                        if(pos != -1){
                                            url = url.substring(0,pos-1);
                                            window.location.replace(url);
                                          
                                        }else{
                                            window.location.reload();
                                        }

					
				}
			}
		});
		
		return false;
	},
	
	openMenu: function($super) {
		$super();
		this.handle.addClassName('listExpand');
	},
	
	closeMenu: function($super){
		$super();
		this.handle.removeClassName('listExpand');
	}
});



/* subscription popup
----------------------------------------------------- */
var Subscription = Class.create(PopupHiddenDiv, {
	fShowContent: function($super) {
		$super();
		new ValidateNewsLetter('subForm', [checkEmpty, checkEmail]);
	}
});

var ValidateNewsLetter = Class.create(ValidateForm, {
	throwErr: function($super) {
		if(this.illegalArr.length > 0){
			alert(this.illegalArr[0].errMsg);
			this.illegalArr[0].focus();
			this.illegalArr = [];
			return false;
		}
		else {
//			$('subForm').onsubmit = this.subscriptForm;
			
			$('subFormEnter').blur();
			var url = $('subForm').action;
			new Ajax.Request(url, {
				method: 'post',
//				asynchronous: false,
				postBody: Form.serialize('subForm'),
				onLoading: function() {
					$('Msg').innerHTML = 'Enviando...';
				},
				onComplete: function(resp) {
					if(resp.responseText == '1') {
						$('Msg').innerHTML = $('Msgok').value;
						setTimeout("subPopup.fClose()", 3000);
					}else{
						$('Msg').innerHTML = $('MsgNok').value;;
					}
				}
			});
				
			return false;
		}
		
	}
});


/* contact pupup
----------------------------------------------------- */

var ContactPopup = Class.create(PopupHiddenDiv, {
	fOpen: function($super) {
		this.fGetClose().innerHTML = this.fGetHandle().innerHTML;
		$super();
	},
	
	fShowContent: function($super) {
		$super();
		Element.addClassName(this.fGetWindow(), 'absolutePopup');
		Element.addClassName(this.fGetHeader(), 'contactOpen');
		Element.addClassName(this.fGetWindowContent(), 'contactContent');
//		$('contactSubmit').onclick = weCallYou;
		new ValiContact('contactForm', [checkEmpty, checkEmail, checkNum, checkSelcValue]);
	},
	
	fClose: function($super) {
		$super();
		this.fGetClose().innerHTML = '';
		Element.removeClassName(this.fGetWindow(), 'absolutePopup');
		Element.removeClassName(this.fGetHeader(), 'contactOpen');
		Element.removeClassName(this.fGetWindowContent(), 'contactContent');
	},
	
	fSetPosition: function() {
		new Position.clone($('contactPopupHandle'), this.fGetWindow(), {setHeight:false, setWidth:false});
	}
});

/*var ContactPopup = Class.create(Menu, {
	openMenu: function($super) {
		$super();
		this.handle.addClassName('contactOpen');
		new ValiContact('contactForm', [checkEmpty, checkEmail, checkNum]);
	},
	
	closeMenu: function($super){
		$super();
		this.handle.removeClassName('contactOpen');
	}

});*/

var ValiContact = Class.create(ValidateForm, {
	throwErr: function(){
		if (this.illegalArr.length > 0) {
			alert(this.illegalArr[0].errMsg);
			this.illegalArr[0].focus();
			this.illegalArr = [];
			return false;
		}
		else {
			var self = this;
			$('contactSubmit').blur();
			var url = $('contactForm').action;
			new Ajax.Request(url, {
				asynchronous: false,
				method: 'post',
				postBody: Form.serialize('contactForm'),
				onCreate: function(){
					$('respMsg').innerHTML = 'sending...';
				},
				onComplete: function(resp){
					if (resp.responseText == '1') {
						$('respMsg').innerHTML =  $('contactOk').value;
						setTimeout(self.hideElement, 5000);
					}
					else {
						$('respMsg').innerHTML  = $('contactNok').value;
						setTimeout(self.hideElement, 5000);
					}
				}
			});
			
			
			
			return false;
		}
	},
	
	hideElement: function() {
		var formContent = $('contactForm');
		Element.hide('popup_Window');
		Element.hide('popup_Overlay');
		$('respMsg').innerHTML = '';
		document.body.appendChild(formContent);
	}
});


/* class AdvancedSearchPopup
----------------------------------------------------- */
var AdvancedSearchPopup = Class.create(PopupURL, {
	fShowContent : function($super) {		
		
		$super();
		datePickerController.create();		
		
		$('quantity').onchange = setQuantityPrice;
		$('perPrice').onchange = setPerPrice;
		$('unitNum').onchange = setUnitNum;
		
		$('advancedWithLogo').onclick = function() {
			var elements = $A(Element.select(Element.up($('advancedWithLogo'), 'fieldset'), 'input.radio'));
			elements.each(function(radio, index) {
				if($('advancedWithLogo').checked) {
					radio.disabled = false;
					Element.removeClassName(radio, 'disabled');
				}
				else {
					radio.disabled = true;
					Element.addClassName(radio, 'disabled');
				}
			});
		}
		
		$('limitedColorLogo').onclick = function() {
				$('limitedColorLogoNum').disabled = false;
				Element.removeClassName($('limitedColorLogoNum'), 'disabled');
		}
		
		var elements = $A(Element.select(Element.up($('advancedWithLogo'), 'fieldset'), 'input.radio'));
		elements.each(function(radio, index) {
			if(radio.getAttribute('id') != 'limitedColorLogo') {
				radio.onclick = function() {
					$('limitedColorLogoNum').disabled = true;
					Element.addClassName($('limitedColorLogoNum'), 'disabled');
				}
			}
		});
		var elementsA = $$('#advancedSearch fieldset.customization legend span');
		var elementsB = $$('#advancedSearch fieldset.customization div.tips');
		if(elementsA.length == elementsB.length) {
			for(var i=elementsA.length-1; i>=0; i--) {
				new HandleTips(elementsA[i], elementsB[i]);
			}
		}
	}
});

/* class ViewPackPopup
----------------------------------------------------- */
var ViewPackPopup = Class.create(PopupURL, {
	fShowContent : function($super) {		
		$super();
		
		var arrayPageScroll = getPageScroll();
		var arrayPageSize = getPageSize();
		var firstChild = Element.firstDescendant(this.fGetWindowContent());
		var innerWidth = Element.getStyle(firstChild, 'width');
		innerWidth = innerWidth ? parseInt(innerWidth) : 400;
		var left = (arrayPageSize[2] - innerWidth)/2 + arrayPageScroll[0];
		
		$('popup_Window').style.left = left + 'px';
	}
})


/* calculator of sidebar
----------------------------------------------------- */
function toFloatWithComma(s) {
	if(typeof s == 'string') {
		return s.replace('.', ',');
	}	
	return s.toString().replace('.', ',');
}

function floatFormat(parentNode, elemClassName) {
	var reg = /\./g;
	var calValues = Element.select($(parentNode), '.' + elemClassName);
	for (var i = calValues.length - 1; i >= 0; i--) {
		calValues[i].value = calValues[i].value.replace(reg, ',');
	}
}

function floatFormat2(parentNode, elemClassName) {
	var reg = /\,/g;
	var calValues = Element.select($(parentNode), '.' + elemClassName);
	for (var i = calValues.length - 1; i >= 0; i--) {
		calValues[i].value = calValues[i].value.replace(reg, '.');
	}
}

function formatFloat(src, pos) {
	return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
}

function unitPriceCal() {
	if(!this.value) return;
	floatFormat('calFieldset', 'calValue');
	if(!$('totalPrice').value && !$('unit').value) return;
	if($('totalPrice').value && !$('unit').value) {
		floatFormat2('calFieldset', 'calValue');
		$('unit').value = $('totalPrice').value / this.value;
		$('unit').value = formatFloat($('unit').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
	if(!$('totalPrice').value && $('unit').value) {
		floatFormat2('calFieldset', 'calValue');
		$('totalPrice').value = this.value * $('unit').value;
		$('totalPrice').value = formatFloat($('totalPrice').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
	if($('totalPrice').value && $('unit').value) {
		floatFormat2('calFieldset', 'calValue');
		$('totalPrice').value = this.value * $('unit').value;
		$('totalPrice').value = formatFloat($('totalPrice').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
}


function totalPriceCal() {
	if(!this.value) return;
	floatFormat('calFieldset', 'calValue');
	if(!$('unit').value && !$('unitPrice').value) return;
	if(!$('unit').value && $('unitPrice').value) {
		floatFormat2('calFieldset', 'calValue');
		$('unit').value = this.value / $('unitPrice').value;
		$('unit').value = formatFloat($('unit').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
	if($('unit').value && !$('unitPrice').value) {
		floatFormat2('calFieldset', 'calValue');
		$('unitPrice').value = this.value / $('unit').value;
		$('unitPrice').value = formatFloat($('unitPrice').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
	if($('unit').value && $('unitPrice').value) {
		floatFormat2('calFieldset', 'calValue');
		$('unitPrice').value = this.value / $('unit').value;
		$('unitPrice').value = formatFloat($('unitPrice').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
}

function unitCal() {
	if(!this.value) return;
	this.value = parseInt(this.value);
	floatFormat('calFieldset', 'calValue');
	if(!$('totalPrice').value && !$('unitPrice').value) return;
	if(!$('totalPrice').value && $('unitPrice').value) {
		floatFormat2('calFieldset', 'calValue');
		$('totalPrice').value = this.value * $('unitPrice').value;
		$('totalPrice').value = formatFloat($('totalPrice').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
	if($('totalPrice').value && !$('unitPrice').value) {
		floatFormat2('calFieldset', 'calValue');
		$('unitPrice').value = $('totalPrice').value / this.value;
		$('unitPrice').value = formatFloat($('unitPrice').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
	if($('totalPrice').value && $('unitPrice').value) {
		floatFormat2('calFieldset', 'calValue');
		$('unitPrice').value = $('totalPrice').value / this.value;
		$('unitPrice').value = formatFloat($('unitPrice').value, 2);
		floatFormat('calFieldset', 'calValue');
	}
}

function setQuantityPrice() {
	$('quantity').value = toFloatWithComma($('quantity').value);
	var quantity = parseFloatWithComma($('quantity').value);
	if(!quantity || isNaN(quantity) ) {
		$('quantity').value = '';
		return;
	}
	
	var perPrice = parseFloatWithComma($('perPrice').value);
	var unitNum = parseInt($('unitNum').value);
	
	if(isNaN(perPrice) && isNaN(unitNum)) {
		return;
	}
	if(isNaN(unitNum)) {
		$('unitNum').value = (quantity/perPrice) ? ((toFloatWithComma(Math.round(quantity /perPrice)))) : '';
		return;
	}
	else {
		$('perPrice').value = (quantity/unitNum) ? ((toFloatWithComma(Math.round(quantity * 100 /unitNum)/100))) : '';
	}
}

function setPerPrice() {
	$('perPrice').value = toFloatWithComma($('perPrice').value);
	var perPrice = parseFloatWithComma($('perPrice').value);
	if(!perPrice || isNaN(perPrice)) {
		$('perPrice').value = '';
		return;
	}
	
	var quantity = parseFloatWithComma($('quantity').value);
	var unitNum = parseInt($('unitNum').value);
	
	if(isNaN(quantity) && isNaN(unitNum)) {
		return;
	}
	if(isNaN(unitNum)) {
		$('unitNum').value = (quantity/perPrice) ? ((toFloatWithComma(Math.round(quantity / perPrice)))) : '';
		return;
	}
	else {
		$('quantity').value = (unitNum * perPrice)? ((toFloatWithComma(Math.round(unitNum * perPrice * 100)/100))) : '';
	}
}

function setUnitNum() {
	$('unitNum').value = parseInt($('unitNum').value);
	var unitNum = $('unitNum').value;
	if(!unitNum || isNaN(unitNum)) {
		$('unitNum').value = '';
		return;
	}
	
	var quantity = parseFloatWithComma($('quantity').value);
	var perPrice = parseFloatWithComma($('perPrice').value);
	
	if(isNaN(quantity) && isNaN(perPrice)) {
		return;
	}
	if(isNaN(quantity)) {
		$('quantity').value = (unitNum*perPrice) ? ((toFloatWithComma(Math.round(unitNum * perPrice * 100)/100))) : '';
		return;
	}
	else {
		$('perPrice').value = (quantity/unitNum) ? ((toFloatWithComma(Math.round(quantity * 100 /unitNum)/100))) : '';
	}
}


/* google search input focus
----------------------------------------------------- */
function searchFocus(idElement) {
	this.ofocus = (typeof idElement == 'string') ? $(idElement) : idElement;
	this.qtxt = this.ofocus.value;
	Event.observe(this.ofocus, 'focus', this.searchOnFocus.bind(this));
	Event.observe(this.ofocus, 'blur', this.searchOnBlur.bind(this));
}

searchFocus.prototype.searchOnFocus = function() {
	if (this.ofocus.value === this.qtxt) {
		this.ofocus.value = '';
	}
	else {
		return;
	}
}

searchFocus.prototype.searchOnBlur = function() {
	if (this.ofocus.value) {
		return;
	}
	else {
		this.ofocus.value = this.qtxt;
	}
}


/* change form element name
----------------------------------------------------- */
function changeName() {
	var thisForm = this.form;
	var elements = Element.select(thisForm, 'input');
	for(var i=elements.length-1; i>=0; i--) {
		elements[i].name = extractPara(elements[i].name, '_', 1);
	}		
	
	elements = Element.select(thisForm, 'select');
	for(var i=elements.length-1; i>=0; i--) {
		elements[i].name = extractPara(elements[i].name, '_', 1);
	}
	return true;
}

function evalValue() {
	$('totalPrice_hide').value = $('totalPrice').value;
	$('unit_hide').value = $('unit').value;
	$('unitPrice_hide').value = $('unitPrice').value;
	floatFormat2('calFieldset', 'hideCalValue');
}

function submitFindProduct() {
//	evalValue();
	changeName.call(this);
}

/*Function
----------------------------*/
function createViewPackPopup(){		
		var url = $('viewPack').href;
		var title = $('viewPack').title ? $('viewPack').title : 'popup';;
		new ViewPackPopup('viewPack', url, {'title': title});
}

/*
----------------------------------------------------- */
var subPopup;
function rootEvents() {
	if($('language')) {
		document.body.appendChild($('language'));
	}
	
	if($('currentLang')) {
		new LanguageList('currentLang', 'langList', 'langItem');
	}
	
	if($('confirmReload')) {
		new CustomLanguageList('currentLang', 'langList', 'langItem');
		$('language').appendChild($('confirmReload'));
	}
	
	if($('contactPopupHandle')) {
		new ContactPopup($('contactPopupHandle'), $('contactForm'));
	}
	
	if($('subscription')) {
		subPopup = new Subscription('subscription', $('subForm'));
	}

	if($('leftbar')) {
		
		new ValidateForm('searchProduct',[checkEmptyLeast]);
		new ToggleHidden('toggleHiddenBtn', 'HiddenBox');
		new HandleTips('searchProductHelp');

		Event.observe($('unitPrice'), 'change', unitPriceCal);
		Event.observe($('totalPrice'), 'change', totalPriceCal);
		Event.observe($('unit'), 'change', unitCal);
		
		$('findProduct').onclick = submitFindProduct.bind($('findProduct'));
	}
	
	if ($('fieldText')) {
		var fieldText = $('fieldText').value;
	}
	
	if($('generalSearch')) {
		new searchFocus('searchSiteValue');
		$('searchSiteBtn').onclick = function() {
			if($('searchSiteValue').value == fieldText) {
				$('searchSiteValue').value = '';
			}
		}
	}
	
	if($('quickSearch')) {
		new searchFocus('quickSearchFormValue');
		$('quickSearchFormValue').onclick = function() {
			if($('quickSearchFormValue').value == fieldText) {
				$('quickSearchFormValue').value = '';
			}
		}
	}
	
	if($('modo')) {
		var url = $('modo').href;
		var title = $('modo').title ? $('modo').title : 'popup';;
		new AdvancedSearchPopup('modo', url, {'title': title});
	}
	
}

Event.observe(document, 'dom:loaded', rootEvents);


