

window.showInquiryForm = function()
{
	$.showFrame("/CustomPages/InquiryForm.aspx", function() { }, 700, 400);
}

$(document).ready( function() { setupPageControls(); });

// Generic method that runs on all pages used to setup custimized controls that may be present on any given page. 
function setupPageControls() {
	$('.howToBuyBtn').click(function() {  window.showInquiryForm(); });
}


function doAjax(service, operation, successFn, data) {
	var requestUrl = 'http://' + window.location.host + '/WebServices/' + service + '/' + operation;
	
	if(data == undefined)
		data = '{}';
	
	$.ajax({
	  type: "POST",
	  contentType: "application/json; charset=UTF-8",
	  url: requestUrl,
	  data: data,
	  dataType: "json",
	  error: function(data, msg, error) { doAjaxLoadError(data, msg, error); },
	  success: successFn
	 });
}

function doSynchronousAjax(service, operation, successFn, data) {
	var requestUrl = 'http://' + window.location.host + '/WebServices/' + service + '/' + operation;

	if (data == undefined)
		data = '{}';

	$.ajax({
		type: "POST",
		contentType: "application/json; charset=UTF-8",
		url: requestUrl,
		data: data,
		async: false,
		dataType: "json",
		error: function(data, msg, error) { doAjaxLoadError(data, msg, error); },
		success: successFn
	});
}

function doAjaxLoadError(data, msg, error) {

	/* check and see if this is a .Net exception object */
	if (data && data.responseText) {
		var errObj = eval("(" + data.responseText + ")");
		var message = errObj.Message;
		var stackTrace = errObj.StackTrace;
		displayErrorMessage(message);
	}
	else {
		displayErrorMessage(msg + error);
	}
}

var errorDialogMarkupInjected = false;
function displayErrorMessage(errorMessage) {

	if (!errorDialogMarkupInjected) {

		$("<div class='global-error-dialog'><h3>Unable to complete requested action</h3><label></label>(click on this box to dismiss)</div>").appendTo("body");
		$('.global-error-dialog').click(function() { $(this).hide() });
		errorDialogMarkupInjected = true;
	}

	$('.global-error-dialog').find("label").text(errorMessage);
	$('.global-error-dialog').show();
}

function maskInput(txt, val, onChangeFn) {
	var fn = function() {var t = $(this); t.removeClass('maskedTxt'); t.val(''); t.unbind('focus', fn); t.unbind('change', fn);};
	txt.val(val);
	txt.addClass('maskedTxt');
	txt.bind('focus', fn); 
	txt.bind('change', fn); 
	
	if(onChangeFn != undefined)
		txt.bind('change', onChangeFn);
}

// Acts like Page.ResolveUrl
function resolveUrl(url) {
	if(url.indexOf('~') == 0)
		return url.substring(1,url.length);
	
	return url;
}

function runFunction(fn) {
    fn();
}


// Fix for Firefox nextSibling (ignores whitespace)
function getNextSibling(startNode)
{
    node = startNode.nextSibling;
    while(node.nodeType != 1)
    {
        node = node.nextSibling;
    }
    return node;
}


// indicates whether or not a given email string is valid.
function isEmailAddressValid(emailAddress) {

	var emailRegxp = /^[a-zA-Z0-9-!#$%&'*+/=?^_`{|}~.]+(?:\.[a-z0-9-!#$%&'*+/=?^_`{|}~]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9-])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9])?$/i;

	return emailRegxp.test(emailAddress);
}

function isMultipleEmailAddressValid(emailAddresses)
{
	var emailRegxp = /^((\s*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*[,;:]){1,100}?)?(\s*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4})*$/;
	
	return emailRegxp.test(emailAddresses);
}

// wraps a string in single quotes and escapes any embedded single quotes.
function prepareAjaxParamString(obj) {

	if (obj)
		return "'" + String(obj).replace(/'/, "\'") + "'";
	else
		return "''";
}

// converts an object map into a JSOn string.
function json2string(strObject) {
 var c, i, l, s = '', v, p;
 switch (typeof strObject) {
 case 'object':
  if (strObject) {
   if (strObject.length && typeof strObject.length == 'number') {
    for (i = 0; i < strObject.length; ++i) {
     v = json2string(strObject[i]);
     if (s) {
      s += ',';
     }
     s += v;
    }
    return '[' + s + ']';
   } else if (typeof strObject.toString != 'undefined') {
    for (i in strObject) {
     v = strObject[i];
     if (typeof v != 'undefined' && typeof v != 'function') {
      v = json2string(v);
      if (s) {
       s += ',';
      }
      s += json2string(i) + ':' + v;
     }
    }
    return '{' + s + '}';
   }
  }
  return 'null';
 case 'number':
  return isFinite(strObject) ? String(strObject) : 'null';
 case 'string':
  l = strObject.length;
  s = '"';
  for (i = 0; i < l; i += 1) {
   c = strObject.charAt(i);
   if (c >= ' ') {
    if (c == '\\' || c == '"') {
     s += '\\';
    }
    s += c;
   } else {
    switch (c) {
     case '\b':
      s += '\\b';
      break;
     case '\f':
      s += '\\f';
      break;
     case '\n':
      s += '\\n';
      break;
     case '\r':
      s += '\\r';
      break;
     case '\t':
      s += '\\t';
      break;
     default:
      c = c.charCodeAt();
      s += '\\u00' + Math.floor(c / 16).toString(16) +
       (c % 16).toString(16);
    }
   }
  }
  return s + '"';
 case 'boolean':
  return String(strObject);
 default:
  return 'null';
 }
}


// A generic lightbox control, that can be used one time in a given page  
// page instance. this control depends on Jquery being present on the page.
//
function GenericLightBoxDialog(id, inrContentNode)
{
	/* Set up internal members */
	this.Id = id;
	this.InrContentNode = inrContentNode;

	var that = this;

	init();

	function init() {
		/* ensure divs are added to outermost body container */
		var content = $("<div id='lightBoxOverlay-" + that.Id + "' style='display: none; background-color: Black; position: absolute; width: 200px; height:200px; top: 0; left: 0; z-index: 1000;' ></div>"
             + "<div id='lightBoxDialog-" + that.Id + "' style='display: none; position: absolute; z-index: 1001;'>"
              + "</div>");
        
 		content.appendTo("form:first");

		$('#lightBoxDialog-' + that.Id).append(that.InrContentNode);
	}

	this.ShowDialog = function(showModal) {
		var win = $(window);
		var body = $("body");
		var doc = $(document);
		var lightBoxOverlay = $("#lightBoxOverlay-" + this.Id);
		var lightBoxDialog = $("#lightBoxDialog-" + this.Id);


		if (showModal) {
			var height;
			if ($(window).height() > doc.height())
				height = $(window).height();
			else
				height = doc.height();
				
			/* set overlay to cover entire screen */
			lightBoxOverlay.height(height).width(body.width());

			/* display the lightbox dialog */
			lightBoxOverlay.fadeTo(0, 0.70).show();
		}

		this.InrContentNode.show();
		lightBoxDialog.show();

		setDivCenterScreen(lightBoxDialog.get(0));
	}
       
   this.CloseDialog = function () {
   	var lightBoxOverlay = $("#lightBoxOverlay-" + this.Id);
   	var lightBoxDialog = $("#lightBoxDialog-" + this.Id);
   	lightBoxOverlay.hide();
   	lightBoxDialog.hide();
   	this.InrContentNode.hide();
   }

   this.UpdateSize  = function () {
   	var lightBoxDialog = $("#lightBoxDialog-" + this.Id);
   	lightBoxDialog.height(this.InrContentNode.height());
   	lightBoxDialog.width(this.InrContentNode.width());
   }
   
   function setDivCenterScreen(div) {
    	var Xwidth = that.InrContentNode.width(); //this.Width;
    	var Yheight = that.InrContentNode.height(); //this.Height;
        var r=div.style; 
        r.height = Yheight + "px";
        r.width = Xwidth + "px";

        var clientHeight, clientWidth;
        if( self.innerHeight ) 
        { 
	        clientWidth = self.innerWidth; 
	        clientHeight = self.innerHeight; 
        } 
        else if( document.documentElement && document.documentElement.clientHeight ) 
        { 
	        clientWidth = document.documentElement.clientWidth; 
	        clientHeight = document.documentElement.clientHeight; 
        } 
        else if( document.body ) 
        { 
	        clientWidth = document.body.clientWidth; 
	        clientHeight = document.body.clientHeight; 
        }
        
        var scrollX = 0; var scrollY = 0;
        if (!document.documentElement.scrollLeft)
           scrollX = document.body.scrollLeft;
        else
           scrollX = document.documentElement.scrollLeft;
        if (!document.documentElement.scrollTop)
           scrollY = document.body.scrollTop;
        else
           scrollY = document.documentElement.scrollTop;     

        var leftOffset = ((clientWidth / 2) - (Xwidth / 2)) + scrollX;
        var topOffset = ((clientHeight / 2) - (Yheight / 2)) + scrollY;
        
        r.position='absolute'; 
        r.top = topOffset + 'px'; 
        r.left = leftOffset + 'px'; 
    }
}

/***************** end GenericLightBoxDialog ****************/

$.fn.center = function(options) {
	/// Pulled from: http://www.west-wind.com/weblog/posts/459873.aspx
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
				container: window,    // selector of element to center in
				completeHandler: null,
				minX: 0,
				minY: 0
			};
			
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;
      
        if (opt.forceAbsolute) {
            if (isWin)
                el.appendTo("body");
            else
                el.appendTo(jWin.get(0));
        }

        el.css("position", "absolute");

        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x < opt.minX ? opt.minX + jWin.scrollLeft() : x + jWin.scrollLeft());
        el.css("top", y < opt.minY ? opt.minY + jWin.scrollTop() : y + jWin.scrollTop());

        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}


$.extend( {
	showFrame: function(src, closeFn, frameHeight, frameWidth, closeSelector) {
		if(closeSelector == undefined)
			closeSelector = '.closer';
		
		var box = $('<div class="m-box" style="background-color: Black; position: absolute; top: 0; left: 0; z-index: 1000;"></div>');
		var loadBox = $('<div style="z-index: 1001;"><h4 style="color: #E1DFE2; margin: 0px;">Loading ... </h4><img src="/resources/images/loadingAnimation.gif" /></div>');
		
		var win = $(window);
		var body = $("body");
		var doc = $(document);
		
		var height;
		if ($(window).height() > $(document).height())
			height = $(window).height();
		else
			height = $(document).height();
			
		box.height(height).width(body.width());
		box.fadeTo(0, 0.70).show();
		body.append(box);
		body.append(loadBox);
		loadBox.center();
				
		var frameBox = $('<div class="m-frame-box" style="z-index: 1002; visibility: hidden;"></div>');
		var frame = $('<iframe src="' + src + '" style="border:0; margin: 0px; padding: 0px;" frameborder="0" marginheight="0" marginwidth="0" scrolling="no"></iframe>');
		
		frame.load(function() { 
			if(frameHeight)
				frame.height(frameHeight);
			else
				frame.height(frame.contents().find('body').height() + 'px');
				
			if(frameWidth)
				frame.width(frameWidth);
			else
				frame.width(frame.contents().find('body').width() + 'px');
			
			frameBox.height(frame.height());
			frameBox.width(frame.width());
			
			frameBox.center({minY: 10});
			loadBox.hide();
			frameBox.css('visibility', 'visible');
			
			frame.contents().find(closeSelector).click(	function() { 
				if(closeFn != undefined)
					closeFn();
				$.fn.clearFrame();
				return false; });
		});	
		
		frameBox.append(frame);
		body.append(frameBox);
	}
});

window.clearFrame = function() 
{
	$.fn.clearFrame();
} 

window.clearFrameAndShowInquireForm = function() 
{
	$.fn.clearFrame();
	setTimeout(window.showInquiryForm, 500);
} 

jQuery.fn.clearFrame = function()
{
	$(".m-frame-box").remove();
	$(".m-box").remove();
}

jQuery.fn.maxLength = function(max){  
    this.each(function(){  
        //Get the type of the matched element  
        var type = this.tagName.toLowerCase();  
        //If the type property exists, save it in lower case  
        var inputType = this.type? this.type.toLowerCase() : null;  
        //Check if is a input type=text OR type=password  
        if(type == "input" && inputType == "text" || inputType == "password"){  
            //Apply the standard maxLength  
            this.maxLength = max;  
        }  
        //Check if the element is a textarea  
        else if(type == "textarea"){  
            //Add the key press event  
            this.onkeypress = function(e){  
                //Get the event object (for IE)  
                var ob = e || event;  
                //Get the code of key pressed  
                var keyCode = ob.keyCode;  
                //Check if it has a selected text  
                var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;  
                //return false if can't write more  
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);  
            };  
            //Add the key up event  
            this.onkeyup = function(){  
                //If the keypress fail and allow write more text that required, this event will remove it  
                if(this.value.length > max){  
                    this.value = this.value.substring(0,max);  
                }  
            };  
        }  
    });  
};  