// JavaScript Document

function MainController(option) {
	this.host = '';
	this.currentPage = '';
	this.mainmenu = option.mainmenu;
	this.submenu = option.submenu;
	this.prefix = option.prefix || '';
	this.forgetPasswdContent = ''
	this.currentInstance = this;
	this.temp_path = '/decoiluzion';
	this.exception = option.exception || new Array();
	this.mainbody = $("body");
	this.mainwindow = $(window);
	this.maindocument = $(document);
	this.currentPopup = '';
	this.popupMask = 'popMask';
	this.init();
}


MainController.prototype.init = function() {
	this.processHost();
	this.setCurrentPage();
}

MainController.prototype.setCurrentInstance = function(instance) {
	this.currentInstance = instance;
}

MainController.prototype.getHost = function() {
	return this.host;
}

MainController.prototype.processHost = function() {
	var pathname = document.location.pathname;
	if(pathname.search(/\/$/) == -1 && pathname.search(/php$/) == -1)
		pathname = pathname + '/';
	this.host = document.location.protocol + '//' + document.location.host + pathname;
	this.host = this.host.replace(/\/[^\/]*.php$/,'/');
}

MainController.prototype.getCurrentPage = function() {
	return this.currentPage;
}

MainController.prototype.setCurrentPage = function() {
	var finalpath = '';
	var pathname = document.location.pathname;
	found = pathname.toLowerCase().match(/\/([^\/]*.php)/);

	if(found) {
		finalpath = found[1];
		for(var i = 0; i < this.exception.length; i++) {
			if(finalpath == this.exception[i].key + ".php")
				finalpath = this.exception[i].value + ".php";
		}
	}
	if(pathname == this.temp_path + '/') {
		finalpath = 'index.php';
	}
	this.currentPage = finalpath;
}

MainController.prototype.getCurrentId = function() {
	var finalId = '';
	var currentPage = this.getCurrentPage();
	var found = currentPage.match(/(.*).php/);

	if(found)
		finalId = found[1];
	
	return this.prefix + finalId;
}

MainController.prototype.processMenu = function() {
	var currentPage = this.getCurrentPage();
	var currentId = this.getCurrentId();
	var anchor_href = '';
	var content = '';
	var currentImg = '';

	$("#"+ this.mainmenu +" a").each(function(idx) {
		anchor_href = $(this).attr("href");
		if( currentPage == anchor_href ) {
			currentImg = $("#" + currentId + " img").attr("src");
			if(currentImg.search(/_hover/) == -1) {
				currentImg = currentImg.replace(/\.png/,'_hover.png');
				$("#" + currentId + " img").attr("src",currentImg);
			}
		}
	});

}

MainController.prototype.manageSubMenu = function(id) {
	$("#" + this.prefix + id).mouseover(function() {
//		$("#sub_" + id).slideDown('fast');
		$("#sub_" + id).css('display','block');
	});
	$("#" + this.prefix + id).mouseleave(function() {
//		$("#sub_" + id).slideUp('fast');
		$("#sub_" + id).css('display','none');
	});
	$("#sub_" + id).mouseleave(function() {
//		$(this).slideUp('fast');
		$(this).css('display','none');
	});
	$("#" + this.mainmenu).mouseleave(function() {
//		$("#sub_" + id).slideUp('fast');
		$("#sub_" + id).css('display','none');
	});
}

MainController.prototype.changeLinks = function() {
	var tmp_url = '';
	var re = /http/;
	var local_host = this.getHost();

	$("a").each(function(idx) {
		if($(this).attr('href').search(re) == -1) {
			tmp_url = local_host + $(this).attr('href');
			$(this).attr('href', tmp_url);
		}
	});
}

MainController.prototype.sendData = function(_arg) {
	var form  = document.getElementById(_arg.form_f);
	var send  = Spry.Widget.Form.validate(form);
	var data = '';
	var curr_icon = '';
	var currObj = this.currentInstance;
	
	if(send) {
		data += $("#" + _arg.form_f).serialize();
		data += "&action=" + _arg.action;
		$.post("_task.php", data,function(data){
			if(data.status) {
				if(_arg.clear)
					form.reset();
				curr_icon = _arg.icon[0];
			}
			else {
				curr_icon = _arg.icon[1];
			}

			currObj.launchPopup({
				type : 'layer',
				nameFile : _arg.filename,
				container : 'pop_message_c',
				icon : {container : 'icon_target', source : curr_icon},
				obj : {width : 597, height : 378, left : 200},
				msg : {place : _arg.content, txt : data.msg}
			});
		}, "json");
	}
}

MainController.prototype.setForgetPasswdContent = function(id) {
	this.forgetPasswdContent = $("#" + id).html();
}

MainController.prototype.getForgetPasswdContent = function() {
	return this.forgetPasswdContent;
}

MainController.prototype.miniPopup = function(_arg) {
	var form  = document.getElementById(_arg.form_f);
	var send  = Spry.Widget.Form.validate(form);
	var currObj = this.currentInstance;
	var data = '';
	
	if(send) {
		data += $("#" + _arg.form_f).serialize();
		data += "&action=" + _arg.action;
		$.post("_task.php", data,function(data){
			$("#" + _arg.content).html(data.msg)
			$("#" + _arg.winpopup).slideDown('fast');
			if(data.status) {
				if(_arg.reloadAll) {
					currObj.setCookie({name : data.cname, value : data.code, expiredays : 1});
					var url = parent.window.location.toString();
					form.reset();
					
					if(_arg.url) {
						parent.window.document.location.replace(_arg.url);
					}
					else {
						if (url.search(/activacion.php/) != -1)
							parent.window.document.location.replace('mi_cuenta.php');
						else 
							parent.window.document.location.reload();
					}
				}
			}
		}, "json");
	}
	
	$("#" + _arg.btn_close).click(function() {
		$("#" + _arg.winpopup).slideUp('fast');
	});
}

MainController.prototype.logout = function(_arg) {
	var currObj = this.currentInstance;

	$.post("_task.php", {action : 'Logout'},function(data){
		if(data.status) {
			currObj.setCookie({name : data.cname, value : '', expiredays : -1});
			var url = parent.window.location.toString();
			parent.window.document.location.replace(url);
		}
		else {
			alert('Problemas con la conexion');
		}
	}, "json");
}

MainController.prototype.showMiniPopup = function(_arg) {
	$("#" + _arg.main).html(this.getForgetPasswdContent());

	$("#" + _arg.content).html('le estaremos enviando su contraseña en breves momentos a su email...');
	
	$("#" + _arg.listener.id).click(_arg.listener.method);
	
	$("#" + _arg.winpopup).slideDown('fast');
	
	$("#" + _arg.btn_close).click(function() {
		$("#" + _arg.winpopup).slideUp('fast');
	});
}

MainController.prototype.goToLocal = function(value, field, url) {
	if(value != '')
		window.location.href = url + field + '=' + value;
}

MainController.prototype.showDetailPanel = function(currentObj) {
	$("#" + currentObj).find(".ver_detalles").show();
}

MainController.prototype.hideDetailPanel = function() {
	$(".ver_detalles").hide();
}

MainController.prototype.getJSFile = function(fileName) {
	$.ajaxSetup({async: false});
	$.getScript('js/' + fileName + '.js');
	$.ajaxSetup({async: true});
}

MainController.prototype.getCSSFile = function(fileName) {
	$("<link/>", {
	   rel: "stylesheet",
	   type: "text/css",
	   href: "estilos/" + fileName + ".css"
	}).appendTo("head");
}

MainController.prototype.hidePopup = function() {
	$("#"+ this.popupMask).hide();
	$("#"+ this.currentPopup).hide();
}

MainController.prototype.launchPopup = function(_arg) {
	var show_mask = (typeof(_arg.showMask) !== 'undefined' ? _arg.showMask : true);
	if(show_mask)
		this.showMask();
	this.currentPopup = _arg.container;
	var top_offset = this.mainwindow.scrollTop();
	
	//	COMPUTE VALUES
	var top = Math.floor((this.mainwindow.height() - _arg.obj.height)/2) + (_arg.obj.top ? _arg.obj.top : 0) + top_offset;
	var left = Math.floor((this.mainwindow.width() - _arg.obj.width)/2) + (_arg.obj.left ? _arg.obj.left : 0);
	var width_value = _arg.obj.width + 30;
	var height_value = _arg.obj.height + 30;
	var width = width_value + 'px';
	var height = _arg.obj.height + 'px';

	//	CREATE CONTAINER
	this.mainbody.append('<div id="'+ _arg.container +'"></div>');
	$("#"+ _arg.container).css({
		'position'	: 'absolute',
		'z-index'	: '9999',
		'overflow'	: 'hidden',
		'display'	: 'none',
		'top'		: top,
		'left'		: left,
		'width'		: width,
		'height'	: height
	});

	if(_arg.type == 'layer')
		this.launchPopupLayer(_arg);
	else if(_arg.type == 'iframe')
		this.launchPopupIframe(_arg);
	else
		alert("Debe especificar un tipo valido");

	$("#"+ _arg.container).show();
//	$("#"+ _arg.container).fadeIn('slow');
}

MainController.prototype.launchPopupIframe = function(_arg) {
	var width_value = _arg.obj.width + 30;
	var height_value = _arg.obj.height + 30;

	//	CREATE IFRAME
	$("#"+ _arg.container).append('<iframe name="iframe_'+ _arg.container +'" id="iframe_'+ _arg.container +'" allowtransparency="1" frameborder="0"></iframe>');
	$("#iframe_"+ _arg.container).attr({
		src	: _arg.nameFile
	}).css({
		'width'	: width_value + 'px',
		'height': height_value +'px'
	});
}

MainController.prototype.launchPopupLayer = function(_arg) {
	//	LOAD POPUP INFO
	$("#"+ _arg.container).load(_arg.nameFile, {}, function() {
		//	SET MESSAGE
		if(_arg.msg)
			$("#"+ _arg.msg.place).html(_arg.msg.txt);
		
		//	SET ICON
		if(_arg.icon)
			$("#"+ _arg.icon.container).attr('src', 'images/iconos/' + _arg.icon.source);
	});
}

MainController.prototype.showMask = function() {
	//	COMPUTE VALUES
	var height = this.maindocument.height() + 'px';
	var width = this.maindocument.width() + 'px';

	//	CREATE CONTAINER
	this.mainbody.append('<div id="'+ this.popupMask +'"></div>');
	$("#"+ this.popupMask).css({
		'position'	: 'absolute',
		'backgroundColor'	: 'white',
		'z-index'	: '9998',
		'overflow'	: 'hidden',
		'opacity'	: 0.75,
		'filter'	: 'alpha(opacity=75)',
		'display'	: 'none',
		'top'		: 0,
		'left'		: 0,
		'width'		: width,
		'height'	: height
	});
	$("#"+ this.popupMask).show();
//	$("#"+ _arg.container).fadeIn('slow');
}

MainController.prototype.getResult = function(container, q_action, q_value) {
	if(q_value) {
		if(q_value == 17) {
			$("#pro_mod").slideDown('fast');
			$("#txt_pro_mod").hide();
			this.getResultRequest(container, q_action, q_value);
		}
		else {
			$("#pro_mod").slideUp('fast');
			$("#pro_mod").html("");
			$("#pro_mod").append('<option value="">Seleccione</option>');
			$("#txt_pro_mod").show();
		}
	}
}

MainController.prototype.getResultRequest = function(container, q_action, q_value) {
	if(q_value) {
		var cbo_result = jQuery("#" + container);
		cbo_result.html("");
		cbo_result.append('<option value="">Cargando...</option>');
	
		jQuery.getJSON("_task.php",{action : q_action, value : q_value},function(data){
			lastResult = data;
	
			cbo_result.html("");
			cbo_result.append('<option value="">Seleccione</option>');
			for(var i in data){
				if(data[i].id) {
					cbo_result.append("<option value='"+ data[i].id +"'>"+ data[i].name +"</option>");
				}
			}
//			$("form.jqtransform").jqTransform();
		});
	}
}

MainController.prototype.goToURL = function(_arg) {
	var curr_icon = _arg.icon[0];
	var currObj = this.currentInstance;
	
	$.post("_task.php", _arg.query, function(data){
		if(data.status)
			window.location.href = _arg.url;

		currObj.launchPopup({
			type : 'layer',
			nameFile : _arg.filename,
			container : 'pop_message_c',
			icon : {container : 'icon_target', source : curr_icon},
			obj : {width : 597, height : 378, left : 50},
			msg : {place : _arg.content, txt : data.msg}
		});
	}, "json");
}

MainController.prototype.checkSession = function(_arg) {
	var currObj = this.currentInstance;
	
	$.post("_task.php", _arg.query, function(data){
		if(data.status) {
			window.location.href = _arg.url;
		}
		else {
			currObj.launchPopup({
				type : 'iframe',
				nameFile : _arg.filename,
				container : _arg.container,
				obj	: _arg.obj
			});
		}
	}, "json");
}

MainController.prototype.setCookie = function(_arg) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+_arg.expiredays);
	document.cookie = _arg.name+ "=" +escape(_arg.value) + ((_arg.expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

MainController.prototype.removeProduct = function(_arg) {
	$.post("_task.php",{action : 'removeProduct', product : _arg.code, destiny : _arg.list, delivery : _arg.delivery}, function(data) {
		if(data.status)
			$("#" + _arg.id).remove();
			$("#" + _arg.shipping_cost).text(data.shipping_cost);
			$("#" + _arg.subtotal).text(data.subtotal);
			$("#" + _arg.total).text(data.total);
			$("#" + _arg.subtotal_div).text(data.subtotal);
			$("#" + _arg.num_prod_div).text(data.num_prod);
			$("#fon_elgie tbody tr").each(function(idx) {
				$(this).find("td:first span").text(idx + 1);
			});

			if(data.num_prod == '000') {
				$("#fon_elgie tbody").html('<tr><td align="center" colspan="7" style="border-right: #A0E3FF 1px dashed;"><span class="contenido_medio">'+ data.msg +'</span></td></tr>');
			}
	}, "json");
}

MainController.prototype.updateProduct = function(_arg) {
	$.post("_task.php", _arg.query, function(data) {
		if(data.status)
			$("#" + _arg.id).fadeOut("fast");
			$("#" + _arg.price).text(data.new_price);
			$("#" + _arg.shipping_cost).text(data.shipping_cost);
			$("#" + _arg.subtotal).text(data.subtotal);
			$("#" + _arg.total).text(data.total);
			$("#" + _arg.subtotal_div).text(data.subtotal);
			$("#" + _arg.num_prod_div).text(data.num_prod);
	}, "json");
}

MainController.prototype.updateTotal = function(_arg) {
	$.post("_task.php", _arg.query, function(data) {
		if(data.status)
			$("#" + _arg.shipping_cost).text(data.shipping_cost);
			$("#" + _arg.subtotal).text(data.subtotal);
			$("#" + _arg.total).text(data.total);
			$("#" + _arg.subtotal_div).text(data.subtotal);
			$("#" + _arg.num_prod_div).text(data.num_prod);
	}, "json");
}

MainController.prototype.updatePriceList = function(_arg) {
	$.post("_task.php", _arg.query, function(data) {
		if(data.status)
			$("#" + _arg.shipping_cost).text(data.shipping_cost);
			$("#" + _arg.subtotal).text(data.subtotal);
			$("#" + _arg.total).text(data.total);
			$("#" + _arg.subtotal_div).text(data.subtotal);
			$("#" + _arg.num_prod_div).text(data.num_prod);
			
			$("#fon_elgie tbody tr").each(function(idx) {
				if(data.price_new[idx] != data.price_old[idx])
					$(this).find(".precio_elig").html('€ ' + data.price_new[idx] + '<br /><span class="precio_old">'+ data.price_old[idx] +'</span>');
					$(this).find(".contenido_medio2").html(data.price_total[idx]);
			});

	}, "json");
}

MainController.prototype.showUpdateButton = function(id) {
	$("#" + id).fadeIn("fast");
}

MainController.prototype.printLayer = function(_arg){
	var charset = (typeof(_arg.charset) !== 'undefined' ? _arg.charset : 'utf-8');
	var css_file = (typeof(_arg.css_file) !== 'undefined' ? _arg.css_file : 'css/estilos.css');
	
	var prtContent = document.getElementById(_arg.content);
	var WinPrint = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=1,status=1,resizable=1');
	WinPrint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
	WinPrint.document.write('<html><head><meta http-equiv="Content-Type" content="text/html; charset='+ charset +'" />');
	WinPrint.document.write('<link href="'+ css_file +'" rel="stylesheet" type="text/css" />');
	WinPrint.document.write('</head><body>');
	WinPrint.document.write(prtContent.innerHTML);
	WinPrint.document.write('</body></html>');
	WinPrint.document.close();
	WinPrint.focus();
	WinPrint.print();
	WinPrint.close();
}

app.MainController = MainController;

