// JavaScript Document
var C_NO_PRICE = "?????";

var resInfo = null;
var resEmail = null;
var priceLinks = null;
var quote_id = "";
var qProducts = [{
	id : 'nc',
	name : 'AdRem NetCrunch 6.5'
}, {
	id : 'ani',
	name : 'AdRem Network Inventory 2'
}, {
	id : 'sm',
	name : 'AdRem Server Manager 7'
}, {
	id : 'sfcon',
	name : 'AdRem sfConsole 2009'
}, {
	id : 'litecon',
	name : 'AdRem LiteCon 2010'
}];

var resInfoTimeCnt = 10;

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

// DOM utilities
function getSubTags(e, tag, tagRef) {
	var node = null;
	var result = [];

	if(e) {// traverse section and find all input and select fields
		node = e.firstChild;
		while(node) {
			if((node.nodeType != 3) && (node.tagName == tag)) {
				result.push( tagRef ? node : node.firstChild);
			}
			node = node.nextSibling;
		}
	}
	return result;
}

function addAnchor(e, href, atext, aclass) {
	e = e.appendChild(document.createElement("a"));
	e.setAttribute("href", href);
	if(aclass) {
		e.setAttribute("class", aclass);
	}
	if(atext !== "") {
		e.appendChild(document.createTextNode(atext));
	}
}

// class DynaText
function DynaText(element) {
	this.tags = getSubTags(element, "P", true);
	this.line = 0;
}

DynaText.prototype.clear = function() {
	this.line = 0;
	for(var i = 0; i < this.tags.length; i++) {
		this.tags[i].firstChild.nodeValue = "";
		while(this.tags[i].childNodes.length > 1) {
			this.tags[i].removeChild(this.tags[i].childNodes[1]);
		}
	}
};

DynaText.prototype.add = function(atext) {
	if(this.line < this.tags.length) {
		this.tags[this.line++].firstChild.nodeValue = atext;
	}
};

DynaText.prototype.addLink = function(href, atext, aclass) {
	addAnchor(this.tags[this.line++], href, atext, aclass);
};
// end of DynaText clss

function resPrintInfo(txt) {
	var node = resInfo.documentElement, tags, i;

	tags = node.getElementsByTagName("address");
	for(i = 0; i < tags.length; i++) {
		txt.add(tags[i].firstChild.nodeValue);
	}
	tags = node.getElementsByTagName("www");
	for(i = 0; i < tags.length; i++) {
		if (tags[i].firstChild) {
  		   txt.addLink(tags[i].firstChild.nodeValue, tags[i].firstChild.nodeValue, "");
		}
	}
	tags = node.getElementsByTagName("email");
	if(tags.length > 0) {
		resEmail = tags[0].firstChild.nodeValue;
	}
    $('#terms').height(247);
	$('#terms').height($('#top-frame').height()-38);	
}

function resellerInfoLoaded(xml) {
  resInfo = xml;
  resPrintInfo(new DynaText(document.getElementById("dealerinfo")));
}

function resellerChanged() {
	if(!this.txt) {
		this.txt = new DynaText(document.getElementById("dealerinfo"));
	}
	if(!this.of) {
		this.of = document.getElementById("orderFrom")
	}
	this.txt.clear();

	if(this.of && (parseInt(this.of.value, 10) === 0)) {
		resEmail = "";
		this.txt.add("Your request will be sent directly to AdRem Software sales team.");
	} else {
		resInfo = null;
		importXML("get-reseller.php?id=" + this.of.value, "resellerInfoLoaded", true, 2000);
		resInfoTimeCnt = 10;
	}
}

function getResellerInfo() {
	var info = resEmail;
	var tags = document.getElementById("orderFrom").getElementsByTagName("OPTION");
	var v = document.getElementById("orderFrom").value;
	
	if(resEmail) {
	  for(var i = 0; i < tags.length; i++) {
	    if(tags[i].value == v) {
	       return tags[i].firstChild.nodeValue + " (" + info + ")";
	    }
	  }
	}
	return info;
}

function isValidType(oInput, oType) {
	switch( oType.toLowerCase() ) {
		case 'select':
			return oInput.selectedIndex;
		case 'number':
			if(!oInput.value) {
				return false;
			}
			for(var mXi = 0; mXi < oInput.value.length; mXi++) {
				if(oInput.value.charAt(mXi) != '' + parseInt(oInput.value.charAt(mXi), 10) + '') {
					return false;
				}
			}
			return true;
		case 'name':
			return ( trim(oInput.value));
		case 'email':
			return (oInput.value && !oInput.value.replace(/[\w\-\+]+(\.[\w\-\+]+)*@([\w\-]+\.)+[a-z]+/i, "") );
	}
}

function showBuyForm(id) {
    var pprefix = $(priceLinks).find('#'+id).attr('name');

	$("#q-buy-links a").remove();
    $(priceLinks).find('#'+id+' link').each(function(index, element) {
	   var pel   = $(element).find(Currency.toLowerCase()),
           price = pel.text(), 
           pid   = pel.attr('pid'),
		   links = $("#q-buy-links"); 
	   
	   	   if ((price !== C_NO_PRICE) && (pid !== C_NO_PRICE)) {
			  $('<a/>', {
				  href: "https://secure.shareit.com/shareit/checkout.html?productid="+pid+"&quickbuy=1",
				  text: pprefix + " " + $(element).attr("edition")
			  }).append( $('<span/>', {
				    "class": "p-link-price",
					"text" :  price
			  })).appendTo(links);
	   }
    });
	
	//alert( 'links =' + $("#q-buy-links").find('a').length);
	$("#q-buy").dialog( "option", "height", Math.min( 280+ $("#q-buy-links").find('a').length * 30, 550));
	quote_id = id;
	$("#q-buy").dialog("open");
}

function submitForm() {

	if((document.qform.name.value === "") || (document.qform.company.value === "") || (document.qform.email.value === "")) {
		alert("Please enter name, company and email!");
		return false;
	}

	if(!isValidType(document.qform.name, "name")) {
		alert("Invalid name format.");
		return false;
	}

	if(!isValidType(document.qform.email, "email")) {
		alert("Invalid email format.");
		return false;
	}

	document.qform.checkfld.value = "1592653589793238";
	document.qform.reseller.value = getResellerInfo();

	if(quote_id === "nc") {
		$("#qproduct").val(qProducts[0].name + " edition: " + $("#nc_edition").val() + " RA:" + $("#nc_racc").val());
	} else if(quote_id === "ani") {
		$("#qproduct").val(qProducts[1].name + " edition: " + $("#ani_edition").val());
	} else if(quote_id === "sm") {
		$("#qproduct").val(qProducts[2].name + " type: " + $("#sm_type").val() + " x " + $("#sm_qty").val());
	} else if(quote_id === "sfcon") {
		$("#qproduct").val(qProducts[3].name + " type: " + $("#sfc_type").val() + " x " + $("#sfc_qty").val());
	} else if(quote_id === "litecon") {
		$("#qproduct").val(qProducts[4].name + " type: " + $("#litecon_type").val());
	}

	//	document.qform.submit();
	$.post("quote.php", $("#qform").serialize(), function(data) {
		$("#dialog-form").dialog("close");
		$("#q-response").html(data);
		$("#q-response").dialog('open');
	});
	return true;
}

function getQuote(product) {
	var qp = $("#qproduct");

	if(qp) {
		for(var i = 0; i < qProducts.length; i++) {
			if(qProducts[i].id === product) {
				qp.val(qProducts[i].name);
				$("#q-" + product).show();
			} else {
				$("#q-" + qProducts[i].id).hide();
			}
		}
	}
	quote_id = product;
	$("#dialog-form").dialog("enable");
	$("#dialog-form").dialog("open");
	$("#name").focus();
}

function initDialogs() {
	$(function(){
	  $("#q-buy").dialog({
		  width : 550,
		  height:500,
		  autoOpen : false,
		  modal : true,
		  buttons : {
  
			  "Close" : function() {
				  $(this).dialog('close');
			  },
			  "Request a Quote" : function() {
				  $(this).dialog('close');
				  getQuote(quote_id);
			  }
		  }
	  });
	  $("#q-response").dialog({
		  width : 550,
		  autoOpen : false,
		  modal : true,
		  buttons : {
			  "Close" : function() {
				  $(this).dialog('close');
			  }
		  }
	  });
	  $("#dialog-form").dialog({
		  height : 575,
		  width : 700,
		  autoOpen : false,
		  modal : true,
		  buttons : {
			  "Submit" : function() {
				  if(submitForm()) {
					  $(this).dialog("disable");
				  }
			  }
		  }
	  });
	});
};

function setupStartFromPrices(){
	$.ajax({
        type: "GET",
	    url: "links.xml",
	    dataType: "xml",
	    success: function(xml) {
			var del, price, sel;
			
			priceLinks = xml;
			$(xml).find('product').each(function(index, element) {
                del   = $("#"+$(element).attr('id')+"-frame"); // document element
				price = $(element).find('starts '+Currency.toLowerCase()).text();
				if (price === C_NO_PRICE) 	{
					price = $(element).find('starts usd').text();				
				};
 			    sel = $(del).find('span');
				$(sel[0]).text(price);
				$(sel[1]).text($(element).find('starts').attr('for'));
            });
	    }
});
}


