
var keepMenuUp = true;
var keepHelpMenuUp = '';
var xmlHttp;

function createXmlHttpRequest() {
	if(window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

function ajaxErrorHandler(queryString, responseText) {
	if(responseText.match(/^RESULTS\:/)) {
		responseText = responseText.replace('RESULTS:', '');
		return responseText.split("\t");
		
	} else if (responseText != '') {
		createXmlHttpRequest();
		xmlHttp.open('POST', '/ajax/ajax_error_handler.php', true);
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");	
		xmlHttp.send('queryString='+escape(queryString)+'&responseText='+escape(responseText));
		
		//if we're in dev
		if(window.location.href.match(/\/\/simplytoimpress\//) ) {
			var result = responseText.replace(/\<br.*\>/gi, "\n");
			alert("URL: " + queryString + "\n\n" + result);
		} else {
			alert("Sorry, the system encountered an error processing your request.  Please try again.");
		}
	}
}

function subMenu(id, onoff) {
	id = id.substr(id.length - 1);
	var bgpos = $('#main_menu_'+id).css('backgroundPosition');
	
	//damn ie
	if(typeof(bgpos) == 'undefined') { bgpos = $('#main_menu_'+id).css('background-position-x') + ' ' + $('#main_menu_'+id).css('background-position-y') };
	
	bgpos = bgpos.split(' ');
	var bgposX = bgpos[0].replace('px', '');
	if(onoff=='on') {
		$('#main_menu_'+id).css('backgroundPosition', bgposX+'px 38px');
		$('#sub_menu_'+id).show();
	} else {
		$('#main_menu_'+id).css('backgroundPosition', bgposX+'px 0px');
		$('#sub_menu_'+id).hide();
	}
	
}

function deleteCookie(name) {
	var date = new Date();
	date.setTime(date.getTime()+(-1*24*60*60*1000));
	document.cookie = name+"=''; expires="+date.toGMTString()+"; path=/";
}

function showHelpMenu(id) {
	document.getElementById('img_'+id).src='/images/personalize/'+id+'_over.gif';
	document.getElementById('div_'+id).style.display='block';
	keepHelpMenuUp = id;
}

function hideHelpAfterDelay(id) {
	setTimeout('hideHelpMenu(\'' + id + '\')', 100);
	keepHelpMenuUp = '';
}

function hideHelpMenu(id) {
	if(id != keepHelpMenuUp) {
		document.getElementById('div_'+id).style.display='none';
		document.getElementById('img_'+id).src='/images/personalize/'+id+'.gif';
	}
}

function showMenu(id) {
	document.getElementById(id).style.display='block';
	keepMenuUp = true;
}
function hideAfterDelay(id) {
	setTimeout('hideMenu(\'' + id + '\')', 500);
	keepMenuUp = false;
}
function hideMenu(id) {
	if(!keepMenuUp) document.getElementById(id).style.display='none';
}


function openwin(url, w, h) {
	w2 = w + 30;
	h2 = h + 60;
	 newwindow = window.open(url,'window1','scrollbars=no,'+
			'menubar=no,height='+h2+',width='+w2+',left=150,top=0,resizable=yes,toolbar=no,'+
			'location=no,status=no');
	 if (w && h) { newwindow.resizeTo(w2,h2); }
	 if (window.focus) {newwindow.focus();}
}


function openwin2(url, options) {
	 newwindow = window.open(url,'window2',options);
	 if (window.focus) {newwindow.focus();}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox
     
     if(key == 13) {
    	 console.log('prevent');
    	 return false;
	}
    return true;
}

/*
function supports_canvas() {
  return !!document.createElement('canvas').getContext;
}
*/

/**
 * Gets the given event's position relative to the document counting the offset if passed
 * @returns a JSON object representing the position {x,y}
 */
function getEvtPos(e, offset)
{
	var pos = {x:0,y:0};
	
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		pos.x = e.pageX;
		pos.y = e.pageY;
	}
	else if (e.clientX || pose.clientY) 	{
		pos.x = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		pos.y = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// If an offset object is given then calculate relative distances
	if(offset) {
		pos.x = pos.x - offset.left;//offsetLeft; // get the X axis of image 
		pos.y = pos.y - offset.top;
	}
    
	return pos;
}

function isInside(pos, div) {
	/*
	console.log(pos);
	console.log(div.offset());
	console.log(div.width(), div.height());
	console.log(pos.x >= div.offset().left);
	console.log(pos.x <= div.offset().left+div.width());
	console.log(pos.y >= div.offset().top);
	console.log(pos.y <= div.offset().top+div.height());
	console.log(pos.x >= div.offset().left &&
			pos.x <= div.offset().left+div.width() && 
			pos.y >= div.offset().top && 
			pos.y <= div.offset().top+div.height());
	*/
	
	return (
		pos.x >= div.offset().left &&
		pos.x <= div.offset().left+div.width() && 
		pos.y >= div.offset().top && 
		pos.y <= div.offset().top+div.height()
		);  
}

function parse_url (str, component) {
    // Parse a URL and return its components  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/parse_url
    // +      original by: Steven Levithan (http://blog.stevenlevithan.com)
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // + input by: Lorenzo Pisani
    // + input by: Tony
    // + improved by: Brett Zamir (http://brett-zamir.me)
    // %          note: Based on http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // %          note: blog post at http://blog.stevenlevithan.com/archives/parseuri
    // %          note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // %          note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
    // %          note: a seriously malformed URL.
    // %          note: Besides function name, is essentially the same as parseUri as well as our allowing
    // %          note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
    // *     example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
    // *     returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
    var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 
                        'relative', 'path', 'directory', 'file', 'query', 'fragment'],
        ini = (this.php_js && this.php_js.ini) || {},
        mode = (ini['phpjs.parse_url.mode'] && 
            ini['phpjs.parse_url.mode'].local_value) || 'php',
        parser = {
            php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
        };
 
    var m = parser[mode].exec(str),
        uri = {},
        i = 14;
    while (i--) {
        if (m[i]) {
          uri[key[i]] = m[i];  
        }
    }
 
    if (component) {
        return uri[component.replace('PHP_URL_', '').toLowerCase()];
    }
    if (mode !== 'php') {
        var name = (ini['phpjs.parse_url.queryKey'] && 
                ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
        parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
        uri[name] = {};
        uri[key[12]].replace(parser, function ($0, $1, $2) {
            if ($1) {uri[name][$1] = $2;}
        });
    }
    delete uri.source;
    return uri;
}

function in_array (needle, haystack, argStrict) {   
    var key = '',
        strict = !! argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}

function toUSD(number) {
    var number = number.toString(), 
    dollars = number.split('.')[0], 
    cents = (number.split('.')[1] || '') +'00';
    dollars = dollars.split('').reverse().join('')
        .replace(/(\d{3}(?!$))/g, '$1,')
        .split('').reverse().join('');
    return dollars + '.' + cents.slice(0, 2);
}
