// JavaScript Document

	function isNull(val){return(val==null);}
	function isUndefined(val){return(val===undefined);}
	
	function isset(val){return !isUndefined(val);}
	function empty(val){return (isNull(val) || isUndefined(val) || val=='')? true : false;}
	
	function LTrim(str){
		if (str==null){return null;}
		str = String(str);
		for(var i=0;str.charAt(i)==" ";i++);
		return str.substring(i,str.length);
	}
	function RTrim(str){
		if (str==null){return null;}
		str = String(str);
		for(var i=str.length-1;str.charAt(i)==" ";i--);
		return str.substring(0,i+1);
	}
	function Trim(str){return LTrim(RTrim(str));}
	
	function isArray(obj) {
	   if (!isUndefined(obj) && obj.constructor.toString().indexOf("Array") == -1)
		  return false;
	   else
		  return true;
	}
	
	function in_array(needle, haystack, argStrict) {
		// http://kevin.vanzonneveld.net
		// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
		// *     returns 1: true
	 
		var found = false, key, strict = !!argStrict;
	 
		for (key in haystack) {
			if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
				found = true;
				break;
			}
		}
	 
		return found;
	}
	
	function is_object(obj){
		if( !empty(obj) && (typeof obj === 'object') ){
			return true;
		}else{
			return false;
		}
	}
	
	function is_numeric(value){  
		return !!isNaN(value);  
	} 




function open_popup(url, window_name, width, height){	
  if(!window_name) window_name='popup';
  if(!width) width='300';
  if(!height) height='300';
  window.open(url,window_name,'width='+width+',height='+height+',resizable=1, scrollbars=1');
}


//Protect agenst frames
function unframe_page(){	
	if(window.top.location.href != window.location.href){ 
		window.top.location.href = window.location.href;
	}
}


function movie_DoFSCommand(command, args) { 
  if (command == "display_text") { 
    obj = MM_findObj(args);
	//alert(obj.style.display);
	obj.style.display = 'block';
  }
}


//Detect the Media Object for flash, WMV, etc...
function getMovieObject(movieName){
  if (window.document[movieName]){
      return window.document[movieName];
  }
  
  if (navigator.appName.indexOf("Microsoft Internet")==-1){
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
	  
  }else{ // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    return document.getElementById(movieName);
  }
}

//Open new window for directions with Google Maps
function getDirections(start, end){
	//replace spaces with +s on start 
	s = new String(start);
	start = s.replace(/ /,"+");

	//replace spaces with +s on end
	e = new String(end);
	end = e.replace(/ /,"+");
	
	window.open("http://maps.google.com/maps?f=d&hl=en&saddr="+ start +"&daddr="+ end +"&z=13&om=1", "googlemapsdirections");
}	
	
	
  //Mark Parent as checked.  (Inputs get checked, and labels get clicked)	
	function trigger_parent (e, lvl, tags) {
		
		if(!lvl) lvl = 4;
		if(!tags) tags = /(label)|(input)/i;
		
		for(x=0;x<lvl;x++){
			//alert(e.tagName);
			if(e.tagName.match( tags )){
				if(	e.tagName.match( /label/i ) ){
					//Click a label tag
					triggerEvent(e, 'click');
				}else{
					//Check the imput tag
					e.checked = 'checked';
				}
				break;
			}
			e = e.parentNode;
		}
	}
	
	
	function confirmDelete( url ) {
		if( confirm("Do you really want to delete selected item.") ){
			document.location.href = url;	
		}
	}


	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function eraseCookie(name) {
		createCookie(name,"",-1);
	}


	function getFileExtension(inputId) { 
		var fileinput = document.getElementById("foo"); 
		if(!fileinput ) return ""; 
		var filename = fileinput.value; 
		if( filename.length == 0 ) return ""; 
		var dot = filename.lastIndexOf("."); 
		if( dot == -1 ) return ""; 
		var extension = filename.substr(dot,filename.length); 
		return extension; 
	}
	

//inputs: 		array or json/string array notation
//class_name:	string
function hightlight_form_row( inputs, class_name ){

	//Reset all elements
	$(".frm_struct li").removeClass('errorRow');
	
	//Mark problse rows
	$.each(inputs, function(key, value) { 
		$("input[name="+value+"], select[name="+value+"], textarea[name="+value+"]").parents(".frm_struct li").addClass('errorRow');
	});
	
}
//Will force input on all fields that do not have the 'validEmpty' class assigned
function validate(dom_id){
	problem_fields = [];
	problem_labels = [];
	
	$("#"+dom_id+" input, #"+dom_id+" select, #"+dom_id+" textarea").each(function(){
		
		//If it is visible, not to be skipped AND it is not already flagged...
		if( $(this).is(':visible') && $(this).attr('type')!='hidden' && !$(this).hasClass('validEmpty') && $.inArray($(this).attr('name'), problem_fields) == -1 ){

			//If it has no value then flag 
			if( $(this).attr('type')=='radio' && !$("input[name='"+$(this).attr('name')+"']").is(':checked') ){
				problem_fields.push( $(this).attr('name') );
			
			}else if( $(this).attr('type')=='checkbox' && empty($("input[name='"+$(this).attr('name')+"']:checked").val()) ){
				problem_fields.push( $(this).attr('name') );
				
			}else if( empty($(this).val()) ){
				problem_fields.push( $(this).attr('name') );
			}
			
			if( $.inArray($(this).attr('name'), problem_fields) > -1){
				label = $(this).parents("li").children('label').html();
				if( !isNull(label) && $.inArray(label.replace(':',''), problem_labels) == -1){
					//alert( JSON.stringify( $(this).parents("li").children('label').html() ) );
					problem_labels.push( label.replace(':','') );
				}
			}
		}
		
	});

	if( problem_fields.length > 0 ){
		hightlight_form_row(problem_fields, 'errorRow');
		
		//Compile validation message
		msg = "The following required questions remain unsnswered:\n";
		$.each(problem_labels, function(key, value) { 
			value = value.replace('<span class="req">*</span>', '');
			msg += "  - "+value+" \n";
		});
		msg += "\n(NOTE: Problem fields are marked in red)";
		
		alert(msg);
		return false;
	}else{
		return true;
	}
}


function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}

function htmlentities(str) {
    var i, output='', len, char='';
    len = str.length;
    for(i=0; i<str.length; i++){
        char = str[i].charCodeAt(0);
		//   Numeric			OR   <, >, and Alphabetic 
		if( (char>47 && char<58) || (char>62 && char<127) ){
			output += str[i];
        }else{
            if( str[i].charCodeAt(0) == 0 ){
				output += ' ';
			}else{
				output += "&#" + str[i].charCodeAt(0) + ";";
			}
        }
    }
    return output;
}


//Extends jQuery to provide the HTML tagname (...like nodeName)
$.fn.tagName = function() {
    return this.get(0).tagName;
}


function update_state_pulldown(state, country_id){
	if( empty(state) ){
		state = "#state";
	}
	if( empty(country_id) ){
		country_id = $("#country").val();
	}
	idclass = state.replace(/\./g, '');
	idclass = idclass.replace(/#/g, '');	
	//alert( state );
	
	
	//Update Options
	var element = $(state);
	var parent  = $(state).parent();
	if( country_id > 0 ){
		
		//Disable input
		$(state).attr('disabled', 'disabled');
		
		//Display loading
		$("#state_status").show();
		
		$.getJSON("../../includes/ajax_handler.php",{_country_id: country_id, model: 'state', method: 'get_states', ajax: 'true'}, function(j){
			//No states found in database... use input/textbox instead
			if( j == false ){
				if( $(state).tagName().toLowerCase() == 'select' ){
					//delete select/pull-down
					$("select#"+idclass).remove();
					
					//create input/textbox replacement
					var textbox = document.createElement('input');
					$(textbox).attr('name', idclass);
					$(textbox).attr('id', idclass);
					$(textbox).attr('disabled', 'disabled');
					
					$(parent).prepend(textbox);				
				}
			}
			//States found.  Populate select/pull-down...
			else{
				if( $(state).tagName().toLowerCase() == 'input' ){
					//delete input/textbox
					$("input#"+idclass).remove();
					
					//create select/pull-down
					var select = document.createElement('select');
					$(select).attr('name', idclass);
					$(select).attr('id', idclass);
					$(select).attr('disabled', 'disabled');	
					
					$(parent).prepend(select);
				}else{
					$(state).html('');
				}
				
				//Create the options
				$.each(j, function(id, data) {
					data.name = html_entity_decode(data.name);
					
					var option = document.createElement('option');
					//$(option).attr('value', data.id);
					$(option).attr('value', htmlentities(data.name));
					$(option).html( htmlentities(data.name) );
					
					$(state).append(option);
				});
				
			}
			
			//Hide loading
			$("#state_status").hide();
			
			//Enable input
			$(state).removeAttr("disabled");
		});	
	}
}