/*************************** Country Selector *****************************/

var linkObject = null;
var trackingNumber = null;
var url;
var dataChanged = false; 

function showCountrySelector(_trackingNumber, _countryType, _url)
{
	var countrySelectorPopup = document.getElementById('countrySelectorPopup');


	var countrySelectorPopupTitle = document.getElementById('countrySelectorTitle');
	countrySelectorPopupTitle.innerHTML = 'Select destination country for shipment ' + _trackingNumber; 
	var scrollY = document.documentElement.scrollTop;
	if(scrollY == null || window.pageYOffset > scrollY)
	{
		scrollY = window.pageYOffset;
	}
	countrySelectorPopup.style.top = (scrollY + ((document.documentElement.clientHeight - countrySelectorPopup.clientHeight) / 2)) + "px";
	countrySelectorPopup.style.left = ((document.documentElement.clientWidth - countrySelectorPopup.clientWidth) / 2) + "px";

	countrySelectorPopup.style.visibility = 'visible';
	
	trackingNumber = _trackingNumber;
	linkObject = document.getElementById(_trackingNumber + _countryType); 
	url = _url;
	document.body.onclick = function() 
		{
			document.getElementById('countrySelectorPopup').style.visibility = 'hidden';
			document.body.onclick = null;
		}
}

function showCompanySelector(_trackingNumber, _countryType, _url)
{
	var countrySelectorPopup = document.getElementById('companySelectorPopup');


	var countrySelectorPopupTitle = document.getElementById('companySelectorTitle');
	countrySelectorPopupTitle.innerHTML = 'Select shipping company for container ' + _trackingNumber; 
	var scrollY = document.documentElement.scrollTop;
	if(scrollY == null || window.pageYOffset > scrollY)
	{
		scrollY = window.pageYOffset;
	}
	countrySelectorPopup.style.top = (scrollY + ((document.documentElement.clientHeight - countrySelectorPopup.clientHeight) / 2)) + "px";
	countrySelectorPopup.style.left = ((document.documentElement.clientWidth - countrySelectorPopup.clientWidth) / 2) + "px";

	countrySelectorPopup.style.visibility = 'visible';
	
	trackingNumber = _trackingNumber;
	linkObject = document.getElementById(_trackingNumber + _countryType); 
	url = _url;
	document.body.onclick = function() 
		{
			document.getElementById('companySelectorPopup').style.visibility = 'hidden';
			document.body.onclick = null;
		}
}

function showSharePopup(_trackingNumber, _link)
{
	if(dataChanged)
	{
		var canReload = confirm('You have changed data recently and shared link is outdated. Reload the page?');
		if(canReload)
		{
			document.location.reload(); 
		}
	}


	var sharePopup = document.getElementById('sharePopup');
	var shareTitle = document.getElementById('shareTitle');
	shareTitle.innerHTML = 'Share tracking info for ' + _trackingNumber;
	var shareLinkText = document.getElementById('shareText');
	shareLinkText.innerHTML = _link;
	
	var scrollY = document.documentElement.scrollTop;
	if(scrollY == null || window.pageYOffset > scrollY)
	{
		scrollY = window.pageYOffset;
	}
	sharePopup.style.top = (scrollY + ((document.documentElement.clientHeight - sharePopup.clientHeight) / 2)) + "px";
	sharePopup.style.left = ((document.documentElement.clientWidth - sharePopup.clientWidth) / 2) + "px";

	sharePopup.style.visibility = 'visible';
	document.body.onclick = function() 
		{
			document.getElementById('sharePopup').style.visibility = 'hidden';
			document.body.onclick = null;
		}
		
	sharePopup.onclick = function(e) 
		{
			
			if(e && e.stopPropagation)
			{
				e.stopPropagation();
			}
			event.cancelBubble = true;
			event.returnValue = false;
			return false;
		}
	shareLinkText.onclick = function() 
		{
			selectAll('shareText');
		}
}

function selectAll(id)
{
	var textArea = document.getElementById(id);
	textArea.focus();
	textArea.select();	
}

function selectCountry(_code, _country)
{
	dataChanged = true; 
	linkObject.href = url + _code + "/" + trackingNumber;
	linkObject.innerText = "via destination country EMS site (" + _country + ")";
	linkObject.target = "_blank";
	
	updateCookies(trackingNumber, "EMS", "dest_country", _code);
}

function selectCompany(_code, _company)
{
	dataChanged = true;
	linkObject.href = url + _code + "/" + trackingNumber;
	linkObject.innerText = "via shipping company site (" + _company + ")";
	linkObject.target = "_blank";
	updateCookies(trackingNumber, "CONT", "company", _code);
}


/*************************** Notes *****************************/
var _notesState = new Array();

function toggleEdit(trackingNumber, trackKind)
{
	var prefix = trackKind + trackingNumber;
	var textBlock = document.getElementById(prefix + "text");
	var editBlock = document.getElementById(prefix + "edit");
	
	
	var notesState = _notesState[prefix];
	if(notesState == null || notesState == 0)
	{
		dataChanged = true;
		_notesState[prefix] = 1;
		editBlock.value = getText(textBlock).trim();
		editBlock.style.display = 'block';
		textBlock.style.display = 'none';
		editBlock.focus();
		editBlock.onblur = function()
		{
			toggleEdit(trackingNumber, trackKind)
		}
	}
	else
	{
		var newNotes = editBlock.value.trim();
		newNotes = newNotes.substr(0, 512);
		updateCookies(trackingNumber, trackKind, "note", Base64.encode(newNotes));
		_notesState[prefix] = 0;
		setText(textBlock, newNotes); 
		editBlock.style.display = 'none';
		textBlock.style.display = 'block';
	}
}

function getText(textBlock)
{
   //var result = textBlock.textContent || textBlock.innerText;
   var result = textBlock.textContent || textBlock.innerHTML;
   result = result.trim();
   result = result.replace(/<BR>/g, "\n");
   result = result.replace(/&nbsp;/g, " ");
   result = result.replace(/&amp;/g, "&");
   //alert("get = " + escape(result));
   return result;
}

function setText(textBlock, text)
{
	//alert("set = " + escape(text));
	if(textBlock.textContent)
	{
		textBlock.textContent = text;
	}
	else
	{
		textBlock.innerText = text; 
	}
}

String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g,"");
}

function deleteShipment(code, trackingNumber)
{
	message = "Do you really want to delete all information about shipment " + trackingNumber + "?";
	if(confirm(message))
	{
		var prefix = code + trackingNumber;
		var block = document.getElementById(prefix);
		block.style.display = 'none';
		eraseCookie(prefix);
	}
}

/*************************** base64 *****************************/
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

/*************************** cookies *****************************/

function updateCookies(trackingNumber, prefix, fieldName, fieldValue)
{
	var cookieKey = prefix + trackingNumber;
	//alert(readCookie(cookieKey) + "\n" + unescape(readCookie(cookieKey)));
	var cookieValue = unescape(readCookie(cookieKey));
	
	var pairs = cookieValue.split("&");
	var valueArray = new Array();
	for(index = 0; index < pairs.length; index++)
	{
		var keyValue = pairs[index].split("=");
		var key = keyValue[0];
		var val = keyValue[1];
		valueArray[key] = val; 	
	}
	
	valueArray[fieldName] = fieldValue;
	
	var newCookieValue = "";

	for(var item in valueArray)
	{
		if(newCookieValue.length > 0)
		{
			newCookieValue += "&";
		}
		
		newCookieValue += item + "=" + valueArray[item];  
	}
	
	createCookie(cookieKey, escape(newCookieValue), 365);
}	

function createCookie(name, value, days) 
{
	if(days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) 
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name, "", -1);
}

function deleteCategoryAllCookies(category)
{
	var canDelete = confirm('do you really want to delete all tracking on this page?');
	if(canDelete)
	{
		var cookies = document.cookie.split(";");
		var namesToDelete = new Array();
		
		for (var i = 0; i < cookies.length; i++)
		{
			var name = cookies[i].split("=")[0].trim();
			if(category == '' || name.indexOf(category) == 0)
			{
				
	  			namesToDelete[namesToDelete.length] = name;
	  		}
	  	}
	  	
	  	for (var i = 0; i < namesToDelete.length; i++)
	  	{
	  		eraseCookie(namesToDelete[i]);
	  	}
	  	
	  	var url = document.location.href;
	  	var index = url.indexOf('?');
	  	if(index != -1)
	  	{
	  		url = url.substr(0, index - 1);
	  	}
	  	document.location.href = url + " ";
  	} 
}
/*************************** date *****************************/
function setDate(id, timestamp)
{
	var elem = document.getElementById(id);
	if(elem != null)
	{
		var date = new Date(timestamp * 1000);
		var content = dateFormat(date, "dd-mmm-yyyy HH:MM");
		elem.innerText = content; 
	}
}

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

/*************************** form *****************************/

function submitForm(formName)
{
	var form = document.getElementById(formName);
	if(form != null)
	{
		form.submit();
	}
}

/*
function submitForm2(formName)
{
		var submitButton = document.getElementById("hiddenSubmit");
		if(submitButton != null)
		{
			submitButton.click();
		}
}
*/
