// Yapta is hiring!
// Interested in javascript/AJAX, HTML, CSS and good web programming?
// Yapta is looking to hire a web developer to help us put together
// simple yet effective and dynamic web interfaces.  Check out
// our job listings at http://www.yapta.com/jobs/.
// Let us know what you think of our code below.

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) // if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
    else
    countfield.value = maxlimit - field.value.length;
}
function toggleView(obj) {
	var el = document.getElementById(obj);
	if (el.style.display != 'none') {
		el.style.display = 'none';
	} else {
		el.style.display = '';
	}
}

function showhideDiv(obj) {
    var el = document.getElementById(obj);
    if (el.style.display == 'none') {
        el.style.display = '';
    }
    else if (el.style.display == '') {
        el.style.display = 'none';
    }

}

function showTheForm() {
    if (document.refundForm) {
        if (document.refundForm.gotRefund.checked == true) {
            showhideDiv('newPrice');
        }
    }
    if (document.boughtForm) {
        if (document.boughtForm.boughtIt.checked == true) {
            showhideDiv('boughtIt');
        }
    }
} 

function showDiv(obj) {
	var el = document.getElementById(obj);
	if (el.style.display == 'none') {
		el.style.display = '';
	}
}


function hideDiv(obj) {
	var el = document.getElementById(obj);
	if (el.style.display == '') {
		el.style.display = 'none';
	}
}


function onlyConfCode(e)
{
	var key = window.event ? e.keyCode : e.which;
	if (key < 32)
		return true;
	var keychar = String.fromCharCode(key);
	reg = /[a-zA-Z0-9]/;
	return reg.test(keychar);
}

function onlyDollarAmount(e)
{
	var key = window.event ? e.keyCode : e.which;
	if (key < 32)
		return true;
	var keychar = String.fromCharCode(key);
	reg = /[0-9\.]/;
	return reg.test(keychar);
}

function onlyNumbers(e)
{
	var key = window.event ? e.keyCode : e.which;
	if (key < 32)
		return true;
	var keychar = String.fromCharCode(key);
	reg = /[0-9]/;
	return reg.test(keychar);
}

function onlyName(e)
{
	var key = window.event ? e.keyCode : e.which;
	if (key < 32)
		return true;
	var keychar = String.fromCharCode(key);
	reg = /[a-zA-Z \.\'\-]/;
	return reg.test(keychar);
}

function nCheck(n) {
    if (n == null){
        return false;
    }
    //var illegalChars = /[\w\s\-\/]+/;
    // allow only letters, numbers, minuses and underscores and  parens()
    //alert(n);
    
    if (!n.match(/^[\w\d\s\-\/i\(\)]+$/)) {
       return false;
    }
    return true;
}

function aCheck(a) {
    if (a==null) {
        return false;
    }

    if (!a.match(/^\w{3}/)){
        return false;
    }
    return true;
}

function dateCheck(d) {
    if (d==null) {
        return false;
    }

    if (!d.match(/\d{2}\/\d{2}\/\d{4}/)){
        return false;
    }
    return true;
}


function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


function isNumeric(string)
{
	var numbers = "0123456789.";
	var isnum=true;
	var num;

	for (i = 0; i < string.length && isnum == true; i++){ 
		num = string.charAt(i); 
		if (numbers.indexOf(num) == -1) {
			isnum = false;
		}
	}

	return isnum;
}

function findLow(arrNums){
	var low = 0;
	for (i = 0; i < arrNums.length; i++)
	{
		num = parseInt(arrNums[i]);
		if(!low && num != 0)
		{
			low = num;
		}else if((num < low) && num != 0){
			low = num;
		}
	}
	return low;
}

function findHigh(arrNums){
	var high = 0;
	for (i = 0; i < arrNums.length; i++)
	{
		num = parseInt(arrNums[i]);
		if(!high && num != 0)
		{
			high = num;
		}else if((num > high) && num != 0){
			high = num;
		}
	}
	return high;
}

function findAverage(arrNums){
	var avg = 0;
	var total = 0;
	var count = 0;

	for (i = 0; i < arrNums.length; i++)
	{
		num = parseInt(arrNums[i]);
		if (num > 0)
		{
			total += num;
			count += 1;
		}
	}
	avg = (total / count);

	return avg;
}

function showDropDown(el, container, menuAlign, horizontalOffset){
	$(container).toggle();	
	$(".menuDropDown").not(container).css("display","none");

	$(".menuDropDown").mouseleave(function(){
		$("body").click(function() {
		    $(".menuDropDown").css("display","none");
			$("body").unbind();
		});    	
	});
	
	$(".multiSelect").mouseenter(function(){
			$("body").unbind();
	});

	
	if (!menuAlign == 'undefined'){
		menuAlign = 'left';
	}

	if(!horizontalOffset == 'undefined'){
		horizontalOffset = 0;
	}

	if (menuAlign=='left')
	{
		offsetTop = 20;
		posTop = $(el).position().top + offsetTop;
		posLeft = $(el).position().left + horizontalOffset;
		$(container).css({ left:posLeft, top:posTop });
	
	}else{
		offsetTop = 20;
		posTop = $(el).position().top + offsetTop;
		posRight = $(el).position().left + $(el).width() - $(container).width() - horizontalOffset;
		$(container).css({ left:posRight, top:posTop });

	}

	return false;
}

function hideDropDown(container){
	$(container).addClass('hidden');
	$(container).css("display","none");
}


function showHidePopup(el, container, wrapperId, wrapperClass){
	var wrapperClass = (wrapperClass == null) ? false : wrapperClass;
	var wrapperId = (wrapperId == null) ? false : wrapperId;

	//hack to fix IE6/7 not supporting z-indexes with absolutely positioned elements inside a relative positioned element.
	if ($.browser.msie){
		$("#airResults .module").css('zIndex','0');
		$(el).closest(".module").css('zIndex','1');
	}
	//end hack

	if(!$(container).hasClass('hidden')){
		hidePopup(container);
		return false;
	}

	offsetTop = $(el).outerHeight() + 17;
	offsetLeft = -10;

	posTop = $(el).position().top + offsetTop;
	posLeft = $(el).position().left + offsetLeft;
	
	// checks for a close button, if <img class="close"/> doesn't exist, we create one.
	if(!$(container + ' img.close').length){
		$(container).append('<img src="/images/close.gif" alt="close" title="close" class="close" onclick="hidePopup(\'' + container + '\');" />');
	}

	// checks for rounded corners, if they don't exist, we create them.
	var addCorners = '';
	if(!$(container + ' span.tl').length){
		addCorners += '<span class="tl"></span>';
	}
	if(!$(container + ' span.tr').length){
		addCorners += '<span class="tr"></span>';
	}
	if(!$(container + ' span.bl').length){
		addCorners += '<span class="bl"></span>';
	}
	if(!$(container + ' span.br').length){
		addCorners += '<span class="br"></span>';
	}

	if (addCorners){
		$(container).append(addCorners);
	}


	
	$(container).css({ left:posLeft, top:posTop });
	$(container).removeClass('hidden');
	$(el).blur(function(e){
		hidePopup('.popup');
	});

	return false;
}

function hidePopup(container){
	$(container).addClass('hidden');
}

function showCal(e){
		$(e).datepicker('show');
}


function roundDown(val,mod) {
    return val - val % mod;
}

function roundUp(val,mod) {
    var m = val % mod;
    return (m>0) ? (val + mod - m) : (val);
}

/* @todo: move to YAPTA.utils once it's in main yapta repos */
function poll(readyFunc,actionFunc,timeoutFunc,interval,timeout) {
    /* Example usage:
     var i=1;
     poll(function (){i++; alert(i); if (i>5){return true;} else{return false;}},
          function(){alert('complete')},
          function(){alert('timed out')},
          1,10)

     @note: interval and timeout are in seconds
      */
    var timeout = timeout || 30;
    var end = (new Date()).getTime() + timeout*1000;
    var handle = null;
    
    intervalFunc = function() {
        /* if exception raised by isready, assume not ready */
        if ((function(){try{return readyFunc()}catch(x) {return false;}})()) {
            clearInterval(handle);
            actionFunc();
        } else if ((new Date()).getTime() > end) {
            timeoutFunc();
            clearInterval(handle);
        }
    };
    
    handle = setInterval("intervalFunc();", interval*1000);
}

function makeJquery(element){
	//checks for common types to create a jquery object from a string or another object
	var e;
	var t = typeof(element);

	if(t == 'object'){
		return $(element);
	}else if(t == 'string'){
		var s = element.substring(0,1);
		if (s == '.' || s == '#'){
			return $(element);
		}else{
			//we'll assume passing of an ID
			return $('#' + element);
		};
	}
	return $(element);
}

var popModal = {
	show: function(modalId, elementId, content, options){
		var w = (typeof(options) != 'undefined' && "width" in options) ? options.width : 280;
		var h = (typeof(options) != 'undefined' && "height" in options) ? options.height : 165;
		var topMargin = (typeof(options) != 'undefined' && "height" in options) ? options.topMargin : 15;
		var elementId = makeJquery(elementId);

		if(!$('#' + modalId).length){
			$('body').prepend('<div id="' + modalId + '" class="popModal" style="width: ' + w + 'px; height: ' + h + 'px;"><div class="popModal-pointer"></div><div class="popModal-close" onclick="popModal.close(\'' + modalId + '\');">close</div><div id="' + modalId + '-content" class="popModal-content"></div></div>');
		}
		
		modalContent = makeJquery(modalId + '-content');
		modalId = makeJquery(modalId);

		if(!modalContent.html().length){
			modalContent.html(content);
		}

		//store data for resize
		if (typeof(window.popModalData) == 'undefined'){
			window.popModalData = [{'modalId':modalId, 'elementId':elementId, 'topMargin':topMargin}];
			$(window).resize(popModal.onResize);
		}else{
			window.popModalData.push({'modalId':modalId, 'elementId':elementId, 'topMargin':topMargin});
		};

		modalId.css(popModal._position(modalId, elementId, topMargin))
		modalId.show();

		return modalId;
	},

	close: function(modalId){
		var modalId = makeJquery(modalId);
		modalId.hide();
	},
	
	_position: function(modalId, elementId, topMargin){
		var dim = {
			'offset': elementId.offset(),
			'height': elementId.height(),
			'width': elementId.width()
		};
		return {top: dim.offset.top + dim.height + topMargin, left: (dim.offset.left + dim.width - modalId.width())};
	},

	onResize: function(){
		if (window.popModalData){
			for(m in popModalData){
				window.popModalData[m].modalId.css(popModal._position(window.popModalData[m].modalId, window.popModalData[m].elementId, window.popModalData[m].topMargin));
			}
		}
	},
	
	update: function(modalId, content){
		contentId = makeJquery(modalId + '-content')
		contentId.html(content);
		return true;
	}
}


