//............................................................................
// &copy; The Sage Group plc 2000   All Rights Reserved.
// $Header: C:\cvsrepo\master/work/asp/_ubiquis/navFuncs.js,v 1.13 2006/06/22 10:37:30 laarn Exp $
//............................................................................

// special hack to anihilate "back" button
window.history.forward(1);

//............................................................................
// Utilities to handle HTML form elements
//............................................................................

function radioGetSelectedValue(radios)
{
	// special case when the radios are not generated
	if (radios == null) return null;
	
	// special case for single radio button, radios is not an array!
	if (radios.length == null && radios.checked)
		return radios.value;
				
	for (var i = 0; i < radios.length; i++) {
		if (radios[i].checked)
			return radios[i].value;
	}
	return null;
}

function radioSelectValue(radios, value)
{
	// special case when the radios are not generated
	if (radios == null) return;
	
	// special case for single radio button, radios is not an array!
	if (radios.length == null) {
		if (radios.value == value)
			radios.checked = true;
		return;
	}
				
	for (var i = 0; i < radios.length; i++) {
		if (radios[i].value == value)
			radios[i].checked = true;
	}
}

function comboGetSelectedValue(combo)
{
	if (combo.selectedIndex < 0) return null;
	return combo.options[combo.selectedIndex].value;
}

function encode64(i)
{
	if (i < 10) return 0x30 + i;
	if (i < 36) return 0x41 + i - 10;
	if (i < 62) return 0x61 + i - 36;
	return i == 62 ? 0x40 : 0x5F;
}

function passwordEncode(str1) {
	var str2 = '$';
	
	for (i = 0; i < str1.length; i++) {
		var code = str1.charCodeAt(i);
		var seed = Math.floor(passwordSeed / (i + 1)) & 0xffff;
		code ^= seed;
		var c1 = encode64((code >> 12) & 0x0f);
		var c2 = encode64((code >> 6) & 0x3f);
		var c3 = encode64((code >> 0) & 0x3f);
		str2 += String.fromCharCode(c1, c2, c3);
	}
	return str2;
}

//............................................................................
// Generic Javascript functions for links and form validation
//............................................................................

function advertize(msg)
{
	window.status = msg;
	return true;
}

function urlUncode(charString)
{
	var res = escape(charString);
	return res.replace(/\+/g,"%2b");
}

function formArgs(form, firstChar, onlyDisabled)
{	var s = "";
	for (var i = 0; i < form.elements.length; i++) {
		var element = form.elements[i];
		var type = element.type;
		var val = null;
		
		
		if (!onlyDisabled || (element.type=='password') || (onlyDisabled && element.disabled))
		{
		switch (element.type) {
		case "radio" :
		case "checkbox" :
			if (element.checked) {
			    val = element.value;
				s += firstChar + element.name + "=" + urlUncode(val);
			}
			break;

		case "password" :
			val = element.value;
			val = passwordEncode(val);
			s += firstChar + element.name + "=" + urlUncode(val);
			break;
		case "select-one" :
			for (var j = 0; j < element.options.length; j++) {
				if (element.options[j].selected){
					val = element.options[j].value;
					break;
				}
			}
			s += firstChar + element.name + "=" + urlUncode(val);
			break;
		default : 
			val = element.value;
			s += firstChar + element.name + "=" + urlUncode(val);
		}
		firstChar = "&";
	}
	}
	return s;
}

function submitForm(form, action)
{
	if (form.method=='get')
	{
		var s = "contents.asp?site=" + siteName + 
		"&window=" + windowName + 
		"&action=" + action;
		s += formArgs(form, "&", false);
		window.location.replace(s);
	}
	else
	{
		 form.action = "contents.asp?site=" + siteName + "&window=" + windowName + "&action=" + action;
		 form.action += formArgs(form, "&", true);
		//alert(form.action);
     	form.submit();
    }
}

function load(action)
{
	//alert("contents.asp?site=" + siteName + "&window=" + windowName + "&action=" + action);
	if (externalMode)
	{
		url = "http://" + host + "/" + siteName + "?";
	}
	else
	{
		url = "contents.asp?site=" + siteName + "&window=" + windowName + "&";
	}
	
	url = url + "action=" + action;
	
	window.location.replace(url);
}

// overrides the method load for the anchor url
function browseAt(anchorName)
{
	window.location.replace("#" + anchorName);
}

// same as window.open but does not return anything, so we can use it directly in a link
function openWindow(url, name)
{
	window.open(url, name);
}

//............................................................................
// Generic navigation utilities (sorting, page by page)
//............................................................................

function sort(collection, atb, sign)
{
	var s = "sort";
	s += "&collection=" + urlUncode(collection);
	s += "&atb=" + urlUncode(atb);
	s += "&sign=" + (sign == "+" ? "%2b" : "-");
	load(s);
}

function gotoPage(collection, page)
{
	load("gotoPage&collection=" + collection + "&page=" + page);
}

//............................................................................
// Functions for custom home and item pages
//............................................................................

function showItemFamily(code, catalogueCode)
{
	if (catalogueCode == null)
		load("showItemFamily&code=" + urlUncode(code));
	else
		load("showItemFamily&code=" + urlUncode(code) + "&catalogueCode=" + urlUncode(catalogueCode));
}

function showItem(code)
{
	load("showItem&code=" + urlUncode(code));
}

function showCart()
{
	load("showCart");
}


function showHome()
{
	load("showHome");
}

function showHomeLang()
{
	load("showHome");
}

function showCatalogue(code)
{
	load("showCatalogue&code=" + urlUncode(code));
}

function registerOnSite()
{
	load("registerNewOtcLogin");
}


//............................................................................
// Misc stuff that will be moved later
//............................................................................

// TODO: create component for add box and move it there later
function formAddItemToCart(form)
{
	var code = form.code.value;
	if (code == "") {
		alert(missingItemCodeAlert);
		return;
	}
	if (form.qty.value == "") {
		alert(missingQuantityAlert);
		return;
	}
	var qty = parseInt(form.qty.value);
	if (isNaN(qty) || qty != form.qty.value || qty <= 0) {
		alert(invalidQuantityAlert + form.qty.value);
		return;
	}
	load("addToCart&code=" + urlUncode(code) + "&qty=" + qty);
}

// TODO: will move this one to addressForm later, shared by orderShipmentSection
function checkAddressForm(form)
{
	if (form.addressLabel != null && form.addressLabel.value == "") { 
		alert(addressLabelEmptyAlert);
		return false;
	}
	if (form.contact.value == "") { 
		alert(contactEmptyAlert);
		return false;
	}
	if (form.address1.value == "") {
		alert(addressEmptyAlert);
		return false;
	}
	if (form.zipCode.value == "" && (form.country == null || form.country.value == countryDefault)) {
		alert(zipcodeEmptyAlert);
		return false;
	}
	if (form.city.value == "") {
		alert(cityEmptyAlert);
		return false;
	}
	if (form.country != null && form.country.value == "") {
		alert(countryEmptyAlert);
		return false;
	}
	if (form.phone.value == "") {
		alert(phoneEmptyAlert);
		return false;
	}
	return true;
}

// TODO: will move this one to addressForm later, shared by orderShipmentSection
function submitAddressForm(form, action)
{
	if (!checkAddressForm(form)) {
		return;
	}
	submitForm(form, action);
}

// DATE

function calendarCompleteYear(year) 
{
	var yearStr = "" + year;
	if (yearStr.length <= 2) {
		if (year < 70) 
			year += 2000;
		else
			year +=1900;
	}
	return year;
}

function calendarIsDate(day, month, year) 
{	
	if (month < 1 || month > 12)  // check month range
	{ 
		return false;
	}
	if (day < 1 || day > 31) 
	{
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) 
	{
		return false
	}
	if (month == 2)  // check for february 29th
	{
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			return false;
		}
	}
	
	return true;
}

function parseNumbers(str)
{
	var numbers = new Array();
	var i = 0;
	while (i < str.length) {
		var len = 0;
		var number = "";
		while (i + len < str.length) {
			var ch = str.charAt(i + len);
			if (ch < '0' || ch > '9')
				break;
			number += ch;
			len++;
		}
		if (len > 0) {
			numbers[numbers.length] = parseInt(number, 10);
			i += len;
		}
		else {
			i++;
		}	
	}
	return numbers;
}

function pad0(src, length)
{
	var result = "" + src;
	while (result.length < length)
		result = "0" + result;
	return result;
}

function countLetters(fmt, i)
{
	var ch = fmt.charAt(i);
	var len = 1;
	while (i + len < fmt.length) {
		if (fmt.charAt(i + len) != ch)
			return len;
		len++;
	}
	return len;
}

function calendarFormat(fmt, numbers)
{
	var result = "";
	var i = 0;
	var d = -1, M = -1, y = -1, H = -1, m = -1;
	var numI = 0;
	while (i < fmt.length) {
		var ch = fmt.charAt(i);
		var len = countLetters(fmt, i);
		switch (ch) {
		case 'd': d = numbers[numI++]; result += pad0(d, len); break;
		case 'M': M = numbers[numI++]; result += pad0(M, len); break;
		case 'y': y = calendarCompleteYear(numbers[numI++]); result += y; break;
		case 'H': H = numbers[numI++]; result += pad0(H, len); break;
		case 'm': m = numbers[numI++]; result += pad0(m, len); break;
		default: result += ch; len = 1; break;
		}
		i += len;
	}
	if (!calendarIsDate(d, M, y))
		return null;
	if (H == -1) // fmt does not contain H
		return result;
	if (H >= 24)
		return null;
	if (m == -1) // fmt does not contain m
		return result;
	if (m >= 60)
		return null;
	return result;
}


function validateDate(field, fmt, acceptEmptyDate)
{
	if(!acceptEmptyDate) {
		if(field.value == "") {
			alert(errorFormatDate);
			return false;
		}
	}
	
	if(field.value == "") {
		return true;
	}
	
	var numbers = parseNumbers(field.value);
	var result = calendarFormat(fmt, numbers);
	if (result == null) {
		alert(errorFormatDate);
		return false;
	}
	field.value = result;
	return true;
}
	


function  Tool_SqlFormatDate(str, formatDate, typeDate) {
	//formatDate : "dm" or "md"
	//typeDate : 0 - date ; 1 - dateTime
	var pattern = null;
	if (typeDate)
		pattern = /\d{2}[\/|\-|\s]\d{2}[\/|\-|\s](\d{2}|\d{4})[\/|\-|\s]\d{2}[\/|\-|\s|:]\d{2}/;
	else
		pattern = /\d{2}[\/|\-|\s]\d{2}[\/|\-|\s](\d{2}|\d{4})/;
	if (!pattern.test(str)) {
			alert(errorFormatDate);
			return "";
	}
	
	var tabDate =  str.split(/[\/|\-|\s|:]/);
	if (formatDate == "dm") {
		if (!Tool_IsDate(tabDate[0], tabDate[1], tabDate[2])) {
			alert(errorFormatDate);
			return "";
		}
	}
	else {
		if (! Tool_IsDate(tabDate[1], tabDate[0], tabDate[2])) {
			alert(errorFormatDate);
			return "";
		}
	}
	
	var result = Tool_CompleteYear(tabDate[2]) + "-" + tabDate[1] + "-" + tabDate[0];
	
	if (typeDate) {
		if (tabDate[3] < 24 && tabDate[4] < 60)
			result +=  " " + tabDate[3] + ":" + tabDate[4];
		else {
			alert(errorFormatDate);
			return "";
		}
	}
	
	return result;
}


//Open calendar
childWindow = null;
eltDateActive = null;
eltDateHiddenActive = null;
formatDate = null;
typeComponent = null;

/**
 * elt :			button
 * eltResultForm :	element receiving the result displayed, type, fmt
 * type :			0 - date | 1 - date & time
 * fmt :			"dm" | "md"
 */


function Resize(win_, width_, height_)
{
	if (document.all)
		win_.resizeTo(width_, height_);
	else
		win_.resizeTo(width_ + 12, height_ + 24);
}

function computeLeft(elt) {
    var left = 0;
	eltTemp = elt;
	if (document.all) {
		// IE stops on document.body test while NS stops on null test.
		while (eltTemp != document.body && eltTemp != null) {
			
			left += eltTemp.offsetLeft;
			eltTemp = eltTemp.offsetParent;
		}
			
		//screenX
		left += window.screenLeft - document.body.scrollLeft;
		if (left > 212)	left -= 212;
	}
	
	return left;
}	
	
	
function computeTop(elt) {
	var top =  0;
	eltTemp = elt;
	if (document.all) {
		// IE stops on document.body test while NS stops on null test.
		while (eltTemp != document.body && eltTemp != null) {
			top += eltTemp.offsetTop;
			eltTemp = eltTemp.offsetParent;
		}
			
		//window.screenY
		top += window.screenTop + 15 - document.body.scrollTop;
	}
	return top;
}

function openCalendar(elt, eltDisplayName, formName, type, fmt)
{
	var eltTemp = null;
	eltDateActive = document.forms[formName][eltDisplayName];
	var name = eltDateActive.name;
	//eltDateHiddenActive = document.forms[formName][name + "Hidden"];

	typeComponent = type;
	formatDate = fmt;
	
	
	var left = computeLeft(elt);
	var top =  computeTop(elt);
		
	//features
	var features = "";
	//features += "fullscreen,"
	features += "toolbar=no,"
	features += "scrollbars=no,"
	features += "width=250,"
	features += "height=180,"
	features += "status=no,"
	features += "resizable=no,"
	features += "alwaysRaised=yes,"
	features += "location=no,"
	
	switch (type) {
		case "date":	
			childWindow = window.open("calendarDate.htm","CALENDAR" + eltDisplayName, features);
			Resize(childWindow, widthWindowCalendar + 10, 162 + 30 + 19);
			if (top > (screen.height - 181)) top -= 196;
			break;
		case "timestamp":
			childWindow = window.open("calendarDate.htm","CALENDAR" +eltDisplayName, features);
			Resize(childWindow, widthWindowCalendar + 10, 186 + 30 + 19);
			if (top > (screen.height - 181)) top -= 220;
			break;
		default :
			childWindow = window.open("calendarDate.htm","CALENDAR" +eltDisplayName, features);
			Resize(childWindow, widthWindowCalendar + 10, 186 + 30 + 19);
			if (top > (screen.height - 181)) top -= 220;
	}
	
	childWindow.moveTo(left,top);
	childWindow.focus();
}

//ELT_FOR_RESULT_DATE.disabled = true

function openZoomImage(elt, url, width, height) {
	var indexLastSlash = url.lastIndexOf("/");
    var indexDot = url.lastIndexOf(".");
    var name = url.substring(indexLastSlash + 1, indexDot);
    var features = "";
    features += "toolbar=no,";
	features += "scrollbars=no,";

//	features += "width=" + (width != null ? width : "300") + ",";
//	features += "height=" + (height != null ? height : "300")  + ",";
	features += "width=320,";
	features += "height=330,";

	features += "status=no,";
	features += "resizable=no,";
	features += "alwaysRaised=yes,";
	features += "location=no,";
    var zoomWindow = window.open(url, name, features);
    
//    zoomWindow.moveTo(computeLeft(elt), computeTop(elt));
}

// Window prompt

function promptBox(maxLength, title)
{
	
	var features = "";
	features += "dialodWidth=500px;"
	features += "dialogHeight=150px;"
	features += "status=no"
	
	var args = new Array();
	args[0] = "" + maxLength;
	args[1] = "" + title;
	args[2] = "" + emptyTemplateName; // TODO
	args[3] = "" + buttonOk;
	args[4] = "" + buttonCancel;
	args[5] = "" + templateNamePrompt;
		
	if (navigator.appName == 'Netscape') 
	{
	    var name='';
	    while (name=='')
	    name=window.prompt(title,'');
	    return name;
	}

	else {
	    var result = showModalDialog("promptBox.htm", args, features);
    	return result;
	}
	
}


function addToCart(code, qty)
{
	load("addToCart&code=" +code + "&qty=" + qty);
}


externalMode = false;

function setExternalMode(pHost, pSiteName)
{
	siteName = pSiteName;
	host = pHost;
	windowName = '';
	externalMode = true;
}

