var addressNotFoundMsg = "<table><tr><td><img src=\"http://whatgaragesale.com.au/images/nav/dialog-warning.png\" /></td><td><span class=\"errMsg\"><b>Address Cannot be found</b></span></td></table>";
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
function gv (element) 
{
	return document.getElementById(element).value;
}
function checkEmailExt(sender)
{	
	if(sender.value != "")
	{
		var emailArray 		 = sender.value.split(".");
		var sizeOfEmailArray = emailArray.length;
		//check if the email end up with .com or .com.au
		if(	(emailArray[sizeOfEmailArray-1] == "com") || 
			((emailArray[sizeOfEmailArray-2] == "com") && (emailArray[sizeOfEmailArray-1] == "au")))
		{
			
		}
		else
		{
			var isValidEmail = confirm('Are you sure your email address is correct?'); 
			if(!isValidEmail) 
			{
				$("contact_email").focus();
			} 
			
		}
	}
	
}

function printDiv(id, url){

	var script = '';
	if(browser=="Microsoft Internet Explorer" && version <= 6)
	{
		var script = " <script>alert(\"If the print window do NOT popup,  please click on the menu bar 'File -> print' to print \");</script> ";
	}
  var content=$(id).innerHTML;
  //alert(content);
var pwin=window.open('','print_content','width=750,height=600,toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');

  pwin.document.open();
  pwin.document.write('<html><head><link href="'+url+'/inc/css/css.php" rel="stylesheet" type="text/css">'+script+'</head><body onload="window.print()">'+content+'</body></html>');
  pwin.document.close();
 
  //setTimeout(function(){pwin.close();},1000);

}
/*
	Clear the suburb and state info
*/
/*function clear_suburb_state (prefix)
{
	$(prefix+"suburb").value = "";
	$(prefix+"state").value = "";
	$(prefix+"lat").value = "";
	$(prefix+"lng").value = "";
}*/

/*
	Validate the add/update garage sale form
*/
function validate_garagesale (id)
{
	var errors = "";
	//alert(v("earlyBird"));
	//if (v("title") == "") errors += " - Missing Headline\n";
	if (v("description") == "") errors += " - Missing Description\n";
	/* todo: check end date is after start date */
	//if (v("addr_street") == "") errors += " - Missing Street Address\n";
	//if (v("addr_postcode") == "") errors += " - Missing Postcode\n";
	//if (v("addr_suburb").innerHTML == "" || v("addr_state") == "") " - Address has not been verified\n";
	if(v("earlyBird") == "" ) errors += " - Missing Earily Bird option!\n";
	if (errors != "")
	{
		alert("You need fix some stuff up:\n"+errors);
		return false;
	}
	else
	{
		$("frm_garagesale"+id).submit();
		return true;
	}
}

function validate_updategaragesale(sender)
{
	var errors = "";
	//var frm = $('frm_'+form+id);
	
	//if (v("title") == "") errors += " - Headline is blank\n";
	if (v("contact_name") == "") errors += " - Contact Name is blank\n";
	if (v("contact_email") == "" || !v("contact_email").match(/@/)) errors += " - Contact Email is not valid\n";
	if (v("contact_phone") == "" || !v("contact_phone").match(/[0-9\s\-\(\)]+/)) errors += " - Contact Phone is not valid\n";
	
	if (v("description") == "") errors += " - Description is blank\n";
	if (($("start_date").value == $("end_date").value) // if on same day (wouldnt matter if days apart)
			&& dtp_2_mins("start") > dtp_2_mins("end")) {// and start before end
		errors += " - Your start time is before your end time\n"; 
	}
	/*if (v("addr_street") == "") errors += " - Street is blank\n";			
	if (v("addr_postcode") == "") errors += " - Postcode is blank\n";
	if (v("addr_suburb") == "") errors += " - Suburb is blank\n";
	if (v("addr_state") == "") errors += " - State is blank\n";*/
	
	if($("earlyBird1").checked == false && $("earlyBird2").checked== false)
	{
		errors += " - Early Bird option is blank\n";
	}
	if($("rainOrShine1").checked == false && $("rainOrShine2").checked== false)
	{
		errors += " - Rain or Shine option is blank\n";
	}
	if(v('how_did_u_find_us') == "")
	{
		errors += " - How You Found Us is blank\n";
	}
	if(v('how_did_u_find_us') == "other" && v('howDidYouFindUsOthersInputBox') == "")
	{
		errors += " - How You Found Us is blank\n";
	}
	//$('addr_street').blur('addr_');
		//alert($('validedAddress').value);
		
	if($('validedAddress').value == "false")
	{
		errors += " - Your address is not valided\n -> To Valid your address, please click on the red marker\n  in the map then click on the button [This is it]";
		document.getElementById('mapExplainId').scrollIntoView(true);
		//$('verify_message_td').style.display = "";
		//$('verify_message').innerHTML = addressNotFoundMsg;
	}

	
	if (errors != "")
	{
		//console.log(v('how_did_u_find_us'));
		alert("You need fix some stuff up:\n"+errors);
	}
	else
	{
		new Ajax.Request('/inc/ajax/ajax.php', {
		method: 'get',
		parameters: {
				action: 'checkWeekDay',
				start: $("start_date").value,
				end: $("end_date").value
			},
			onSuccess: function (r) {
				if(r.responseText == "N")
				{
					var isSubmit = confirm ("Those garage sale days you have selected contain weekdays , Are you sure to continue?")
					if(isSubmit)
					{
						
						$("jsSubmitBtn").name = sender.name;
						$("jsSubmitBtn").value = sender.value;

						$("addGrageSaleForm").submit();
					}
				}
				else
				{
					
					$("jsSubmitBtn").name = sender.name;
					$("jsSubmitBtn").value = sender.value;

					$("addGrageSaleForm").submit();
				}
			}
		});
	}

}

function validate (sender) {
	var errors = "";
	
	switch (sender.id) {
		case 'frm_garagesale_search':
			if ($('keywords').value == '' || $('keywords').value == ' ') {
				alert('Type in something to search for first.\n');
				return false;
			}
			break;
	}
}


/************************************
	Events
*************************************/
function check_time (sender, start, end) {
	// start = hour + (pm ? 12 : 0) + minutes	
	var start_time = time2mins(get_time(start));
	//start_time -= (start_time >= (24 * 60)) ? (12 * 60) : 0;
	var finish_time = time2mins(get_time(end));
	
	if (start_time >= finish_time) {
		/*alert($(start+'_ampm').selectedIndex);
		if ($(start+'_ampm').selectedIndex == 0) {
			$(end+'_ampm').options[1].selected = "selected";
			check_time(sender, start, end);
		}*/
		
		// set finish to start + 5mins, if not later than
		if (v(start+"_minutes") == "55") {
			//if (minutes == 55) then go hour + 1 minute = 0
			// if 11:55am
			if (start == "11:55") {
				$(end+"_hours").options[11].selected = "selected";
				$(end+"_minutes").options[0].selected = "selected";
				$(end+"_ampm").options[1].selected = "selected";
			} else {
				$(end+"_hours").options[($(start+"_hours").selectedIndex+1)%12].selected = "selected";
				$(end+"_minutes").options[0].selected = "selected";
			}
		} else {
			// else hour + 0, minute + 1
			$(end+"_hours").options[$(start+"_hours").selectedIndex].selected = "selected";
			$(end+"_minutes").options[($(start+"_minutes").selectedIndex+1)%12].selected = "selected";
			$(end+"_ampm").options[$(start+"_ampm").selectedIndex].selected = "selected";
		}
		
		finish = get_time(end);
	}
	//$(prefix+"duration").innerHTML = "Duration: "+calc_duration(start, finish);
		
	}
	function get_time (prefix) {
		var hour = parseInt(v(prefix+"_hours")) + ((v(prefix+"_ampm") == "pm") ? 12 : 0);
		var minute = parseInt(v(prefix+"_minutes"));
		
		return hour+":"+minute;
	}
	function time2mins (time) {
		// eg. time = 13:22 = 13 * 60 + 22 = 802
		var time = time.split(":");
		var mins = (parseInt(time[0]) * 60) + parseInt(time[1]);
		
		// if hour is 12 or 24, take 12 from it
		mins -= (mins >= (24 * 60) || (mins >= (12 * 60) && mins < (13 * 60))) ? (12 * 60) : 0;
	
		return mins;
}


function btn_back_onclick (sender, form) {
	switch (form) {
		case 'featureitems':
			document.location.href = "?Nav=NGS&stage=1&back";
			break;
		case 'summary':
			document.location.href = "?Nav=NGS&stage=2&back";
			break;
		case 'moreOptions':
			//document.location.href = "?Nav=NGS&stage=2&back";
			$("featureDiv").style.display = "block";
			break;
		case 'backToStage1':
			document.location.href = "?Nav=NGS&stage=1&back";
		
	}
}

function dtp_2_mins (prefix)
{
	var minutes = parseInt($(prefix+"_minutes").value);
	minutes += (parseInt($(prefix+"_hours").value) % 12) * 60;
	minutes += ($(prefix+"_ampm").value == 'pm')? 12 * 60 : 0;
	
	return minutes;
}


/* Add a featured item */
function add_featured_item (sender) {
	$("frm_featureditem").submit();
}


function show_frm_featureditem (sender) {
	$("show_frm_featureditem").style.display = "none";
	$("frm_featureditem_container").style.display = "";
}

/* finished editing featured items, go back to garagesale_editor */
/*function done_featureditems_onclick (sender) {
	document.location = "garagesale_editor.php";
}
*/

// only allow price chars
function price_only (sender, e) {	
	// get the key that was pressed
	if (!e) e = window.event;	
	var key;
	if (e.keyCode) {
		key = e.keyCode;
	} else if (e.which) {
		key = e.which;
	}
	var char = String.fromCharCode(key);
	
	//alert(key);
	
	// check for a valid key (control keys and numbers)
	var valid = ((key == null) 
			|| (key == 0) || (key == 8) /*|| (key == 9)*/ /*|| (key == 13)*/ || (key == 27) // null, backspace, tab, enter, esc
			|| (key == 190 && sender.value.indexOf('.') == -1) // .
			|| (("0123456789").indexOf(char) > -1));
	if (!valid) return false;

	return true;
}

function closeDiv(divId)
{
	$(divId).style.display = "none";
}


//Validation Parts
var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail (s) 
{
    return String(s).search (isEmail_re) != -1;
}


function validateFeatureItemForm()
{
	
		var errors = "";
		//initilize all values 
		var name  		= $("frm_featureditem").name.value;
		var photo 		= $("frm_featureditem").photo.value;
		var price 		= $("frm_featureditem").price.value;
		var description = $("frm_featureditem").description.value;
		if(photo == "")
		{
			errors += "You haven't selected an image to add \n";
		}
		if(name == "")
		{
			errors += "Name Can Not Be Blank! \n";
		}
		
		if(description == "")
		{
			errors += "Description Can Not Be Blank! \n";
		}
		
		
		if(errors == "")
		{
			$("frm_featureditem").submit();
		}
		else
		{
			alert(errors);
		}
	

		
}
//following code is for add garage sale page\
/*@Function Name: calculatePrice
 *@Function Description: This function will be executed whenever users click thisWeekend radio button or this and next weekend radio button 
 *						 on the adding garageslae page. This functions will be mainly just call an ajax file to calculate the total price of garagesale 
 *						 based on users selection.
 *						
 *@Params:	sender		 Parameter of this function is the button object.
 *
 *
 *@Return Type:	None
 *@Author: Jian Han
 *@Date: 09/10/08
 */

function calculatePrice(sender)
{
	var senderValue = $(sender).value;
	
	new Ajax.Request('/inc/ajax/calculate_price_ajax.php', {
		method: 'get',
		parameters: {
			action: 'calculatePrice',
			week: senderValue
		},
		onSuccess: function (r) {
			$("totalPrice").value = r.responseText;
		}
	});
}

function howDidYouFindUsOthers(sender)
{
	/*var value = sender.value;
	if(value=="others")
	{
		$("howDidYouFindUsOthersInputBox").style.display="block";
		//display the input box
	}
	else
	{
		$("howDidYouFindUsOthersInputBox").value="";
		$("howDidYouFindUsOthersInputBox").style.display="none";
	}*/
	var value = sender.value;
	if(value=="others" || value=="other")
	{
		
		document.getElementById("howDidYouFindUsOthersInputBox").style.display="block";
		//display the input box
	}
	else
	{
		document.getElementById("howDidYouFindUsOthersInputBox").value="";
		document.getElementById("howDidYouFindUsOthersInputBox").style.display="none";
	}
	
}

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 redirect(url)
{
	window.location = url;
}

function submitform(formName)
{
  document.formName.submit();
}

function clearSubField(sender)
{
					
	//$("'.$rand_name.'").value="";
	//$js .= '	eid("refineSearchResults").innerHTML = "HELLO";';

	
	//alert(eid("search_region").value);
	//var getRegions = eid("search_region").value.split("-");
	//alert(bits[0]+" | "+bits[1]);		
	//alert(eid("search_region").value);		
		
	if(eid("search_region").value != "")
	{
		
		if( eid("secondary_search") != null  && eid("secondary_search").value != '')
		{
			var search_region = eid("secondary_search").value;
		}
		else
		{
			var search_region = eid("search_region").value;
		}
		//alert(bits[0]);
		if(sender.id == 'search_region')
		{
			eid("refineSearchResults").innerHTML = jLoader();
		}
		else
		{
			eid("refineSecondarySearch").innerHTML = jLoader();	
		}
		new Ajax.Request("/inc/ajax/searchAjax.php", {
			method: "get",
			parameters: {
				action: "getRegions",
				searchArea: search_region,
				topSearchArea: eid("search_region").value,
				seed: seed()
			},
			onSuccess: function (r)
			{
				if(sender.id == 'search_region')
				{
					eid("refineSearchResults").innerHTML = r.responseText;
				}
				else
				{
					eid("refineSecondarySearch").innerHTML = r.responseText;	
				}
			}
		});
	}
	else
	{
		eid("refineSearchResults").innerHTML = "";
		eid("refineSecondarySearch").innerHTML = "";
	}
			
}

function jValidateCompleteAddress(field)
{
	//alert(eid(field).value);
	var address = eid(field).value;
	if(address == ''){
		eid(field).value = 'Type your address here';
		eid('validedAddress').value = false;
	}
	else{
		eid("mapTr").style.display = '';
		eid("mapExplainId").innerHTML = "We need you to confirm your address on the map. Click on the marker and then click \"This is it\" to confirm. You can drag the marker if you like.";
		initializeMapAdvertise(address+', Australia');
	}
}

function jValidateCompleteAddressEnter(field, e)
{
	var pressedKey;
 	if (document.all)	{ e = window.event; }
	if (document.layers || e.which) { pressedKey = e.which; }
 	if (document.all)	{ pressedKey = e.keyCode; }
	if( pressedKey == 13)
	{
		jValidateCompleteAddress(field);
	}
}
