var headPort;
var p2p = false;
var url = "http://www.icontainers.com";
var transType = "FCL";
var detPort;
var volume;
var weight;
var zipcode;
var prepaid;
var impExp = "E";
var hazarous = false;
var domain = false;
var firsItem;

jQuery.noConflict();

jQuery(document)
		.ready(
				function() {
					if (document.domain != "localhost") {
						domain = document.domain;
					}
					 //var cookies = document.cookie.split(";");
					//Delete_Cookie("icon.hash", "/", ".icontainers.com");
					//Delete_Cookie("icon.cityArrival", "/", "www.icontainers.com");

					  /*  for (var i = 0; i < cookies.length; i++) {
					        var cookie = cookies[i];
					        var eqPos = cookie.indexOf("=");
					        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
					        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
					    }*/
					loadData();
					jQuery('.numbersOnly').keyup(function() {
						this.value = this.value.replace(/[^0-9\.]/g, '');
					});
					jQuery
							.ajax({
								url : url + '/main/api',
								dataType : 'jsonp',
								data : 'method=departurePort&id_branch=1',
								success : function(msg) {
									jQuery
											.each(
													msg,
													function(i, item) {
														jQuery("#comboHead")
																.append(
																		jQuery(
																				'<option>',
																				{
																					value : item.id_country_origin
																							+ item.id_city_origin
																				})
																				.text(
																						item.des_city_origin_es));
														jQuery("#comboHead")
																.val(headPort)
																.attr(
																		'selected',
																		true);
													});
								}
							});
					jQuery("#detPort")
							.autocomplete(
									{
										source : function(request, response) {
											jQuery
													.ajax({
														url : "http://www.icontainers.com/main/api",
														dataType : "jsonp",
														crossDomain : true,
														data : {
															method : "arrivalPort",
															id_branch : "1",
															impexp : "E",
															depPort : headPort,
															depCountry : "ES",
															arrPort : request.term
														},
														success : function(data) {
															if (!data.length) {
																data
																		.push({
																			label : "NO HAY RESULTADOS",
																			id : 0
																		});
																response(jQuery
																		.map(
																				data,
																				function(
																						item) {
																					return {
																						label : item.label,
																						value : item.id
																					};
																				}));
															} else {
																firsItem = data[0];
																response(jQuery
																		.map(
																				data,
																				function(
																						item) {
																					return {
																						label : item.des_city_det
																								+ ' ('
																								+ item.des_country_det
																								+ ')',
																						value : item.id_country_det
																								+ item.id_city_det
																					};
																				}));
															}
														}
													});
										},
										minLength : 2,
										select : function(event, ui) {
											if (ui.item.value != 0) {
												detPort = ui.item.value;
												jQuery("#detPort").val(
														ui.item.label);
												jQuery("#iq_volume")
														.removeAttr('disabled');
												jQuery("#iq_weight")
														.removeAttr('disabled');
												changeAutoCss(jQuery("#iq_volume"));
												changeAutoCss(jQuery("#iq_weight"));
											}
											return false;
										},
										change: function(event, ui){
											if(ui.item == undefined && firsItem != undefined){
											detPort = firsItem.id_country_det
											+ firsItem.id_city_det;
											jQuery("#detPort").val(firsItem.des_city_det
													+ ' ('
													+ firsItem.des_country_det
													+ ')');
											}
										},
										error : function(i, msg) {
											alert(msg);
										}
									});

					jQuery("#headInput")
							.autocomplete(
									{
										source : function(request, response) {
											jQuery
													.ajax({
														url : "http://www.icontainers.com/main/api",
														dataType : "jsonp",
														data : {
															method : "departurePort",
															id_branch : "1",
															zipcode : request.term
														},
														success : function(data) {
															if (!data.length) {
																data
																		.push({
																			label : "NO HAY RESULTADOS",
																			id : 0
																		});
																response(jQuery
																		.map(
																				data,
																				function(
																						item) {
																					return {
																						label : item.label,
																						value : item.id
																					};
																				}));
															} else {
																firsItem = data[0];
																response(jQuery
																		.map(
																				data,
																				function(
																						item) {
																					return {
																						label : item.nm_state_city
																								+ "  ("
																								+ item.id_zipcode
																								+ ")",
																						value : item.id_zipcode
																					};
																				}));
															}
														}
													});
										},
										minLength : 2,
										select : function(event, ui) {
											if (ui.item.value != 0) {
												zipcode = ui.item.value;
												jQuery("#headInput").val(
														ui.item.label);
												jQuery("#detPort").removeAttr(
														'disabled');
												changeAutoCss(jQuery("#detPort"));
											}
											return false;
										},
										change: function(event, ui){
											if(ui.item == undefined && firsItem != undefined){
											zipcode = firsItem.id_zipcode;
											jQuery("#headInput").val(firsItem.nm_state_city
													+ "  ("
													+ firsItem.id_zipcode
													+ ")");
											}
										}
									});

					jQuery("#headInput").val(zipcode);
					jQuery("#iq_volume").val(volume);
					jQuery("#iq_weight").val(weight);
					jQuery("#iq_import").click(changeImpExp);

					jQuery('#instant-quote-form input[type="text"]').each(function() {inputDescription(this);});

					login();

				});

function inputDescription(input) {

	if (jQuery(input).val() == "") {
		input.value = jQuery(input).attr('title');
		changeAutoCss(input);

		jQuery(input).focus(function() {
			if (input.value == jQuery(input).attr('title')) {
				input.value = '';
				jQuery(input).removeClass('text-label');
			}
		});

		jQuery(input).blur(function() {
			if (input.value == '') {
				input.value = jQuery(input).attr('title');
				jQuery(input).addClass('text-label');
			}
		});
	}
	;
}

function changeImpExp() {
	if (impExp == "E") {
		jQuery("#detPortlbl").fadeOut(
				300,
				function() {
					jQuery("#detPortlbl").html(
							"¿D&oacute;nde est&aacute; la mercanc&iacute;a?");
					jQuery("#detPortlbl").fadeIn(300);
				});
		jQuery("#headInputlbl")
				.fadeOut(
						300,
						function() {
							jQuery("#headInputlbl")
									.html(
											"¿A d&oacute;nde quieres enviar tu mercanc&iacute;a?");
							jQuery("#headInputlbl").fadeIn(300);
						});
		impExp = "I";
	} else {
		jQuery("#detPortlbl")
				.fadeOut(
						300,
						function() {
							jQuery("#detPortlbl")
									.html(
											"¿A d&oacute;nde quieres enviar tu mercanc&iacute;a?");
							jQuery("#detPortlbl").fadeIn(300);
						});
		jQuery("#headInputlbl").fadeOut(
				300,
				function() {
					jQuery("#headInputlbl").html(
							"¿D&oacute;nde est&aacute; la mercanc&iacute;a?");
					jQuery("#headInputlbl").fadeIn(300);
				});
		impExp = "E";
	}
	;
}

function changeHazarous() {
	if (hazarous) {
		hazarous = false;
	} else {
		hazarous = true;
	}
	;
}

function getCity(city, field) {
	jQuery.ajax({
		url : url + '/main/api',
		dataType : 'jsonp',
		data : 'method=getCity&city=' + city,
		success : function(msg) {
			jQuery(field).val(msg.nm_city);
		}
	});
};

function login() {
	var hash = Get_Cookie("icon.hash");
	if (hash != undefined) {
		jQuery.ajax({
			url : url + '/main/api',
			dataType : 'jsonp',
			data : {
				method : "login",
				user : undefined,
				password : undefined,
				hash : hash
			},
			success : function(msg) {
				if (msg != "error") {
					loginSuccess(msg);
				}
			}
		});
	}/*
		 * else if(Get_Cookie("icon.hashtemp") == undefined){ hashTemp(); }
		 */
}

function loginPsw() {

	jQuery.ajax({
		url : url + '/main/api',
		dataType : 'jsonp',
		data : {
			method : "login",
			user : jQuery('#user').val(),
			password : jQuery('#password').val(),
			hash : null
		},
		success : function(msg) {
			if (msg != "error") {
				loginSuccess(msg);
			} else {
				showError('Usuario o contraseña incorrecta', '');
			}
		}
	});
}

function loginSuccess(login) {
	jQuery("#loginDiv").fadeOut(300, function() {
		jQuery("#loginDiv").remove();
	});
	jQuery("#specialBlock").append("<input type='checkbox' id='iq_prepaid' />");
	jQuery("#specialBlock").append(
			"<span id='prepaidlbl' class='title-input-2'>FOB</span>");
	jQuery("#specialBlock")
			.append("<input id='iq_hazarous' type='checkbox' />");
	jQuery("#specialBlock").append(
			"<span id='hazarouslbl' class='title-input-2'>IMO</span>");
	Set_Cookie("icon.hash", login.hash, 3600 * 24 * 7, '/', domain, '');

	jQuery("#logDiv").append(
			"Bienvenido " + login.entity.nm_legal
					+ " <a href='' onClick='logOut()'>(log out)</a>");
	if (prepaid == "f") {
		jQuery("#iq_prepaid").attr("checked", "checked");
	}
	if (hazarous == "true") {
		jQuery("#iq_hazarous").attr("checked", "checked");
	}
	jQuery("#iq_hazarous").click(changeHazarous);

}

function logOut() {
	jQuery("#logDiv").empty();
	//var oneYearLater = new Date( -1);
	//Set_Cookie("icon.hash", "",  oneYearLater.toGMTString(), '/', domain, '');
	//Set_Cookie("icon.hash", "",  oneYearLater.toGMTString(), '/', "www.icontainers.com", '');
	Delete_Cookie("icon.hash", "/", domain);
}

function hashTemp() {
	Set_Cookie("icon.hashtemp", hex_sha1(new Date().getTime()), 3600 * 24 * 7,
			'/', domain, '');
}

function changeAutoCss(input) {
	if (jQuery(input).attr('disabled') == 'disabled') {
		jQuery(input).addClass('text-label');
		jQuery(input).removeClass('text-label-black');
	} else {
		jQuery(input).addClass('text-label-black');
		jQuery(input).removeClass('text-label');
	}
};

function changeHeadPort(port) {
	headPort = jQuery(port).val();
	if (headPort == '') {
		jQuery("#detPort").attr('disabled', 'disabled');
		jQuery("#iq_volume").attr('disabled', 'disabled');
		jQuery("#iq_weight").attr('disabled', 'disabled');
		changeAutoCss(jQuery("#detPort"));
		changeAutoCss(jQuery("#iq_volume"));
		changeAutoCss(jQuery("#iq_weight"));
	} else {
		jQuery("#detPort").removeAttr('disabled');
		changeAutoCss(jQuery("#detPort"));
	}
};

function p2pChange(value) {
	if (jQuery("#checkp2p").attr("checked") !== undefined) {
		p2p = true;
		jQuery("#headInput").fadeOut(300, function() {
			jQuery("#comboHead").fadeIn(300);
		});
	} else {
		p2p = false;
		jQuery("#comboHead").fadeOut(300, function() {
			jQuery("#headInput").fadeIn(300);
		});
	}
};

function searchRates() {

	// volume = jQuery("#iq_volume").val().replace(/[^0-9\.]/g, '');
	// weight = jQuery("#iq_weight").val().replace(/[^0-9\.]/g, '');
	resetOldCookie();
	if (jQuery("#iq_prepaid").attr("checked") !== undefined) {
		prepaid = "f";
	} else {
		prepaid = "t";
	}

	if (p2p && (headPort == null || headPort.length !== 5)) {
		showError('Choose a pick up location', '');
		return false;
	}
	if (!p2p && (zipcode == null || zipcode.length !== 5)) {
		showError('Choose a pick up location', '');
		return false;
	}
	if ((detPort == null || detPort.length !== 5)) {
		showError('Choose where are you shipping', '');
		return false;
	}
	/*
	 * if (transType !== 'FCL') { if (volume < 0.1) { showError('Enter a valid
	 * volume', ''); return false; } if (weight < 1) { showError('Enter a valid
	 * weight', ''); return false; } }
	 */

	if (p2p) {
		Set_Cookie('icon.cityDeparture', headPort, 3600 * 24 * 7, '/', domain,
				'');
		Delete_Cookie('icon.zipCode', '/', '');
	} else {
		Set_Cookie('icon.zipCode', zipcode, 3600 * 24 * 7, '/', domain, '');
		Delete_Cookie('icon.cityDeparture', '/', '');
	}
	Set_Cookie('icon.cityArrival', detPort, 3600 * 24 * 7, '/', domain, '');
	Set_Cookie('icon.FcloLcl', transType, 3600 * 24 * 7, '/', domain, '');
	Set_Cookie('icon.way', 'AIRSEA', 3600 * 24 * 7, '/', domain, '');
	Set_Cookie('icon.hazarous', hazarous, 3600 * 24 * 7, '/', domain, '');
	Set_Cookie('icon.ImpExp', impExp, 3600 * 24 * 7, '/', domain, '');
	Set_Cookie('icon.prepaid', prepaid, 3600 * 24 * 7, '/', domain, '');
	// Set_Cookie('icon.volume', volume, 3600 * 24 * 7, '/', domain,
	// '');
	// Set_Cookie('icon.weight', weight, 3600 * 24 * 7, '/', domain,
	// '');
	Set_Cookie('icon.search', 't', 30, '/', domain, '');
	Set_Cookie('icon.p2p', p2p, 3600 * 24 * 7, '/', domain, '');

	window.location = "/main/espere-por-favor";
};

function typeChange(value) {
	if (jQuery(value).val() == 'FCL') {
		jQuery("#iq_volume").hide();
		jQuery("#iq_weight").hide();
		jQuery("#iq_weightlbl").hide();
		jQuery("#iq_volumelbl").hide();
		jQuery("#searchButton").addClass('searchButtonfcl').removeClass(
				"searchButton");
		;
	} else {
		jQuery("#iq_volume").show();
		jQuery("#iq_weight").show();
		jQuery("#iq_weightlbl").show();
		jQuery("#iq_volumelbl").show();
		jQuery("#searchButton").addClass('searchButton').removeClass(
				"searchButtonfcl");
	}
	transType = jQuery(value).val();
};

function showError(pa1, pa2) {
	jQuery("#error-message:ui-dialog").dialog("destroy");
	jQuery("#error-message").dialog({
		modal : true,
		title : 'Error',
		buttons : {
			Ok : function() {
				jQuery(this).dialog("close");
			}
		}
	});
	jQuery("#error-message #pa1").text(pa1);
	jQuery("#error-message #pa2").append(pa2);
};

function loadData() {

	// Load the cookie content
	if (Get_Cookie('icon.cityDeparture') != null) {
		headPort = Get_Cookie('icon.cityDeparture');
	}
	if (Get_Cookie('icon.p2p') != null) {
		p2p = Get_Cookie('icon.p2p');
	}
	;
	if (Get_Cookie('icon.FcloLcl') != null) {
		transType = Get_Cookie('icon.FcloLcl');
	}
	;
	if (Get_Cookie('icon.cityArrival') != null) {
		detPort = Get_Cookie('icon.cityArrival');
	}
	;
	if (Get_Cookie('icon.volume') != null) {
		volume = Get_Cookie('icon.volume');
	}
	;
	if (Get_Cookie('icon.weight') != null) {
		weight = Get_Cookie('icon.weight');
	}
	;
	if (Get_Cookie('icon.zipCode') != null) {
		zipcode = Get_Cookie('icon.zipCode');
	}
	;
	if (Get_Cookie('icon.prepaid') != null) {
		prepaid = Get_Cookie('icon.prepaid');
	}
	;
	if (Get_Cookie('icon.ImpExp')) {
		impExp = Get_Cookie('icon.ImpExp');
	}
	;
	if (Get_Cookie('icon.hazarous') != null) {
		hazarous = Get_Cookie('icon.hazarous');
	}

	if (jQuery("#detPort") != null) {
		getCity(detPort, jQuery("#detPort"));
	}
	;

	if (transType == 'FCL') {
		jQuery("#iq_fcl").attr("checked", "checked");
		typeChange(jQuery("#iq_fcl"));
	} else if (transType == 'AIR') {
		jQuery("#iq_air").attr("checked", "checked");
		typeChange(jQuery("#iq_air"));
	}

	if (p2p == "true") {
		jQuery("#checkp2p").attr("checked", "checked");
	}
	p2pChange(null);

	if (prepaid == "f") {
		jQuery("#iq_prepaid").attr("checked", "checked");
	}
	if (impExp == "I") {
		jQuery("#iq_import").attr("checked", "checked");
		impExp = "E";
		changeImpExp();
	}
	if (hazarous == "true") {
		jQuery("#iq_hazarous").attr("checked", "checked");
	}

	jQuery("#detPort").removeAttr('disabled');
	jQuery("#iq_volume").removeAttr('disabled');
	jQuery("#iq_weight").removeAttr('disabled');
	changeAutoCss(jQuery("#detPort"));
	changeAutoCss(jQuery("#iq_volume"));
	changeAutoCss(jQuery("#iq_weight"));

}

function Set_Cookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	 * if the expires variable is set, make the correct expires time, the
	 * current script below will set it for x number of days, to make it for
	 * hours, delete * 24, for minutes, delete * 60 * 24
	 */
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));

	document.cookie = name + "=" + escape(value)
			+ ((expires) ? ";expires=" + expires_date.toGMTString() : "")
			+ ((path) ? ";path=" + path : "")
			+ ((domain) ? ";domain=" + domain  : "")
			+ ((secure) ? ";secure" : "");
};

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( var i = 0; i < a_all_cookies.length; i++) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if (cookie_name == check_name) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no =
			// sign, that is):
			if (a_temp_cookie.length > 1) {
				cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g,
						''));
			}
			// note that in cases where cookie is initialized but no value, null
			// is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) {
		return null;
	}
};

function resetOldCookie(){
	var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var aux1 = cookie.split("=");
        if(aux1[0] != null){
            var aux2 = aux1[0].split(".");
            if(aux2[0] == " icon" && aux2[1] != "hash" && aux2[1] != "hashtemp"){
                var name = cookie.split("=")[0].replace(/^\s+|\s+$/g, '');
                Delete_Cookie(name, "/", "www.icontainers.com");
            }
        }
    }
}

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
	if (Get_Cookie(name)){
		var aux1 = name + "=" + ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=" : "")
		+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		document.cookie = aux1;
		var aux2 = name + "=" + ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=.icontainers.com" : "")
		+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		document.cookie = aux2;
		var aux3 = name + "=" + ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=.www.icontainers.com" : "")
		+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		document.cookie = aux3;
		var aux4 = name + "=" + ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=icontainers.com" : "")
		+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		document.cookie = aux4;
		var aux5 = name + "=" + ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=www.icontainers.com" : "")
		+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		document.cookie = aux5;
	}

};


