function submitFrm(frm) {
	document.forms[frm].submit();
}
function SearchMe(e){
	if(e.keyCode == 13){
		if(document.frmsearch.txtsearch.value==""){
			alert("Enter Search Value");
			return false;
		}
		return true;
	}
}

function isEmpty(strval) {
    if (strval == "" || strval == null || !isNaN(strval) || strval.charAt(0) == ' ')
    {
    return false;
    }
	else
	return true;
  }

//function to check valid email address
function isValidEmail(strEmail){
  validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
  strEmail = strEmail;
   // search email text for regular exp matches
    if (strEmail.search(validRegExp) == -1) 
   {
     return false;
    } 
    return true; 
}

function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

function IsNumeric(strString)
{
   var strValidChars = "0123456789.";
   var strChar;
   var blnResult = true;
   if (strString.length == 0) return false;
   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
	  {
	  strChar = strString.charAt(i);
	  if (strValidChars.indexOf(strChar) == -1)
		 {
		 blnResult = false;
		 }
	  }
   return blnResult;
}

function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return newnumber; // Output the result to the form field (change for your purposes)
}

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 numberFormat(strval, nosdecimalplace)
{
	var result = strval.toFixed(nosdecimalplace);
	return result;
}

function frmContactUsValidate()  {
	var err="";	
	if(!isEmpty(document.eContactusForm.fullname.value))
		err+="Full Name\n";	
	if(!isEmpty(document.eContactusForm.emailaddress.value))
		err+="Email Address\n";
	else if(!isValidEmail(document.eContactusForm.emailaddress.value))
		err+="Invalid Email Address!\n";
	if(!isEmpty(document.eContactusForm.comments.value) || document.eContactusForm.comments.value=="(please type in your comments):")
		err+="Comments\n";	
		
	if(err!="") {
		alert("Following field(s) are required!\n----------------------------\n"+err);
		return false;
	}
	return true;
}

//var selectedPackage = "";
function Calculate(dm)
{
	var strBoatFt = parseFloat(dm.boatLength.value);
	var strPrice = 0;
	var strMonth = 0;
	var strAdditionalPrice = 0;
	
	var TotalAmount = 0;
	if(trim(dm.boatLength.value)=="") {	
		strBoatFt = 0;
	}

	if(dm.boatLength.value != '') {
		if(IsNumeric(dm.boatLength.value)==false) {
		  alert("Boat Length - Use valid number.");
		  dm.boatLength.focus();
		  return;
		}
	}
	
	for (var i = 0; i < dm.rdpackagefees.length; i++){
	  if (dm.rdpackagefees[i].checked) {
		  
		 if(editPosting == false) {
			setImageUploadLimit(i+1);
		 }
		 
		 setVideoUploadLimit(i+1);
		 
		 strPrice = dm.rdpackagefees_price[i].value;
		 strMonth = dm.rdpackagefees_month[i].value;
		 strAdditionalPrice = dm.rdpackagefees_additionalprice[i].value;
		 break;
	  }
	} // end of for loop
  	
	////////dm.txtadditionalprice.value = "$" + "" + numberFormat(parseFloat(strAdditionalPrice),2);
	TotalAmount =  ((strBoatFt * parseFloat(strPrice))*parseInt(strMonth)) + parseFloat(strAdditionalPrice);	
	
	/** Total Amount Calculated **/
	TotalAmount = numberFormat(roundNumber(TotalAmount,2),2);	
	dm.txtamount.value = "$" + "" + TotalAmount;
}


function setImageUploadLimit(packageType) {
	var maxfile = 0;
	if(packageType == 1 || packageType == 4 || packageType == 7) { //Gold
		maxfile = 3-noOfImages;
	} else if(packageType == 2 || packageType == 5 || packageType == 8) { //Platinum
		maxfile = 4-noOfImages;
	} else if(packageType == 3 || packageType == 6 || packageType == 9) { //Diamond
		maxfile = 5-noOfImages;
	}
	$file = '<input id="largeimage" type="file" name="largeimage[]" class="multi" accept="jpg|jpeg|gif|png" maxlength="'+ maxfile +'" />';
	$("#dvFile").html($file);
	$("input[type=file].multi").MultiFile();
}

function setVideoUploadLimit(packageType) {
	if(packageType == 1 || packageType == 4 || packageType == 7) { //Gold
		$("#VideoArea").css("display", "none");
	} else if(packageType == 2 || packageType == 5 || packageType == 8) { //Platinum
		$("#VideoArea").css("display", "block");
		$("#dvVidFile").html('<input type="file" name="videoFile" id="videoFile" />');
		$("#videoFile").uploadify({
			'uploader'       : 'scripts/uploadify.swf',
			'script'         : 'uploadvideo.php',
			'cancelImg'      : 'images/cancel.gif',
			'folder'         : 'uploads',
			'buttonText'     : 'UPLOAD VIDEO',
			'queueID'        : 'fileQueue',
			'fileDesc'       : 'Video Files',
			'fileExt'        : '*.flv;*.avi;*.mp3;*.mp4;*.wmv;*.dat;*.mov;*.mpeg;*.rm',
			'auto'           : true,
			'multi'          : false,
			'sizeLimit'      : '26214400',
			'fileDataName'   : 'videoFile',
			'onSelect'       : function(){
									$("#btnGoStep4N").attr("disabled", "disabled");
									return true;
								},
			'onCancel'       : function(){
									$("#btnGoStep4N").attr("disabled", "");
									return true;
								},
			'onComplete'     : function(event, ID, fileObj, response, data) {
									var msg = response.split("~");
									if(msg[0] == "success") {
										$("#videoID").val(msg[1]);	
									} else if(msg[0] == "fail") {
										alert("Error on uploading video");
									}
									$("#dvVidFile").hide();
									$("#fileQueue div.cancel").hide();
									$("#btnGoStep4N").attr("disabled", "");
									return true;
								},
			'onError'		: function(event, queueID, fileObj, errorObj) {
									alert("Error uploading file #" + fileObj.name + ". Please contact Rentbyboater.");
									return true;
								}
		});
	} else if(packageType == 3 || packageType == 6 || packageType == 9) { //Diamond
		$("#VideoArea").css("display", "block");
		$("#dvVidFile").html('<input type="file" name="videoFile" id="videoFile" />');
		$("#videoFile").uploadify({
			'uploader'       : 'scripts/uploadify.swf',
			'script'         : 'uploadvideo.php',
			'cancelImg'      : 'images/cancel.gif',
			'folder'         : 'uploads',
			'buttonText'     : 'UPLOAD VIDEO',
			'queueID'        : 'fileQueue',
			'fileDesc'       : 'Video Files',
			'fileExt'        : '*.flv;*.avi;*.mp3;*.mp4;*.wmv;*.dat;*.mov;*.mpeg;*.rm',
			'auto'           : true,
			'multi'          : false,
			'sizeLimit'      : '52428800',
			'fileDataName'   : 'videoFile',
			'onSelect'       : function(){
									$("#btnGoStep4N").attr("disabled", "disabled");
									return true;
								},
			'onCancel'       : function(){
									$("#btnGoStep4N").attr("disabled", "");
									return true;
								},
			'onComplete'     : function(event, ID, fileObj, response, data) {
									var msg = response.split("~");
									if(msg[0] == "success") {
										$("#videoID").val(msg[1]);	
									} else if(msg[0] == "fail") {
										alert("Error on uploading video");
									}
									$("#dvVidFile").hide();
									$("#fileQueue div.cancel").hide();
									$("#btnGoStep4N").attr("disabled", "");
									return true;
								},
			'onError'		: function(event, queueID, fileObj, errorObj) {
									alert("Error uploading file #" + fileObj.name + ". Please contact Rentbyboater.");
									return true;
								}
		});
	}
}

function deleteImage(anc, imgId, packageType) {
	var ids = imgId + ","+ $("#deletedImage").val();
	$("#deletedImage").val(ids);
	$(anc).parent("div").remove();

	var maxfile = $("#largeimage").attr("maxlength") + 1;
	$file = '<input id="largeimage" type="file" name="largeimage[]" class="multi" accept="jpg|jpeg|gif|png" maxlength="'+ maxfile +'" />';
	$("#dvFile").html($file);
	$("input[type=file].multi").MultiFile();
	return false;
}

function frmMemberCreatePostingValidate(dm)  {
	var err="";	
	var packageselected = 0;
	if(!isEmpty(dm.txtname.value))
		err+="Give the posting a name\n";
	if(trim(dm.cbboattype.value)=="")
		err+="Vessel Type\n";
	if(dm.cbsize.value == "")
		err+="Size\n";
	if(!isEmpty(document.getElementById("cbuses").value))
		err+="Uses\n";
	if(!isEmpty(dm.cbenginetype.value))
		err+="Engine Type\n";
	
	if(IsNumeric(dm.txtboatft.value)==false)
	{
	  err+="Boat Ft - Use valid number eg: 123456789\n";
	 
	}
	else if(parseInt(dm.txtboatft.value)<=0) {
		err+="Boat Ft - Please enter value greater than 0 (zero)\n";
	}
	
	/* For Package */
	for (var i = 0; i < dm.rdpackagefees.length; i++){
	  if (dm.rdpackagefees[i].checked){
		 packageselected = 1;
		 break;
	  }
	} // end of for loop
	if (packageselected<=0) {
		 err+="Please select atleast one package.";
	}
	/* For Package */
	
	if(err!="") {
		alert("Following field(s) are required!\n----------------------------\n"+err);
		return false;
	}
	return true;
}

//Added by Subash Tamang on March 18 2009, Wednesday
function doConfirm() {
	if(confirm("Are you sure you want to cancel this posting?")) {
		return true;
	}
	return false;
}

function changePerPageResultNo(elm) {
	document.forms['frmAdvanceSearch'].bpp.value = elm.value;
	document.forms['frmAdvanceSearch'].submit();
}

function changePerPageResultNoAdv(elm) {
	document.forms['frmAdvanceSearch'].bpp.value = elm.value;
	document.forms['frmAdvanceSearch'].submit();
}

function showInquireWindow(bid, boatName) {
	var page = encodeURI("boat_inquire.php?bid="+bid+"&boat_name="+boatName);
	window.open(page, "InquireWindow", "menubar=0,scrollbars=0,toolbar=0,resizable=1,width=500,height=575");
}

function showBusinessWindow() {
	var page = encodeURI("business-card.php");
	window.open(page, "BusinessCardWindow", "menubar=0,scrollbars=0,toolbar=0,resizable=0,width=500,height=350");
}

function showInquireReplyWindow(iid, subject) {
	var page = "boat_inquire_reply.php?iid="+iid+"&subject="+subject;
	window.open(page, "InquireReplyWindow", "menubar=0,scrollbars=0,toolbar=0,resizable=0,width=400,height=192");
}

function showCalendar(bid) {
	var page = "calendar.php?bid="+bid;
	window.open(page, "Calendar", "location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=300,height=250");
}

function validateInquireForm(frm) {
	if(frm.fname.value == "") {
		alert("Please enter your First Name");
		frm.fname.focus();
		return false;
	} else if(frm.lname.value == "") {
		alert("Please enter your Last Name");
		frm.lname.focus();
		return false;
	} else if(frm.email.value == "") {
		alert("Please enter your email");
		frm.email.focus();
		return false;
	} else if(!echeck(frm.email.value)) {
		alert('Please enter valid email address');
		frm.email.focus();
		return false;
	} else if(frm.phone.value == "") {
		alert("Please enter your phone number");
		frm.phone.focus();
		return false;
	} else if(frm.begin_date.value == "") {
		alert('Please enter begin date');
		frm.begin_date.focus();
		return false;
	} else if(frm.end_date.value == "") {
		alert('Please enter end date');
		frm.end_date.focus();
		return false;
	} else if(frm.people.value == "") {
		alert("Please provide number of people");
		frm.people.focus();
		return false;
	} else if(frm.ofchildren.value == "") {
		alert("Please provide number of children");
		frm.ofchildren.focus();
		return false;
	} else if(frm.boating_experience.value == "") {
		alert("Please provide your boating experience");
		frm.boating_experience.focus();
		return false;
	} else if(frm.inquireMessage.value == "") {
		alert("Please type your enquiry message");
		frm.inquireMessage.focus();
		return false;
	}
	return true;
}

function echeck(email) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
        return true;
    }
	return false;
}

function gotoPage(page) {
	var pageNo = document.getElementById("gotopage").value;
	if(pageNo == "") return;
	var loc = page+"?&cp="+pageNo;
	window.location = loc;
}

function goLastMonth(month, year) {
	// If the month is Januaru, decrement the year
	if(month == 1) {
		--year;
		month = 13;
	}
	//document.location.href = 'calendar.php?month='+(month-1)+'&year='+year;
	$('#basicModalContent').load("calendar.php?bid="+this.id+'&month='+(month-1)+'&year='+year);
}
function goNextMonth(month, year) {
	// If the month is December, increment the year
	if(month == 12) {
		++year;
		month = 0;
	}
	//document.location.href = 'calendar.php?month='+(month+1)+'&year='+year;
	$("div.loading").html("Loading....").fadeIn("fast");
	$('#basicModalContent').load("calendar.php?bid="+this.id+'&month='+(month+1)+'&year='+year,'', function(){$("div.loading").fadeOut("fast");});
}

function replyMessage() {
	var msg = jQuery.trim($("#message").val());
	if(msg == "") {
		alert("Please write message....");
		$("#message").focus();
		return false;
	}
	$str = $("#frmReply").serialize();
	$("div.loading").fadeIn("normal");
	$.ajax({
		type:"POST",
		url: "boat_inquire_reply.php",
		data: $str,
		success: function($data){
			$("div.loading").fadeOut("normal");
			if($data == "fail") {
				alert("Error Sending Message....");
			} else {
				$("#message").val("");
				$("#tbl_message_thread").append($data).fadeIn("normal");
			}
		}
	});
	return false;
}

function deleteMessage(elm, mid) {
	if(confirm("Are you sure you want to delete this message?")) {
		$str = "mid="+mid;
		$("div.loading").html("Deleting Message....").fadeIn("normal");
		$.ajax({
			type:"POST",
			url: "message_delete.php",
			data: $str,
			success: function($data){
				$("div.loading").fadeOut("normal");
				if($data == "fail") {
					alert("Error Deleting Message....");
				} else {
					$(elm).parent().parent().next("tr").next("tr").hide("normal").remove();
					$(elm).parent().parent().next("tr").hide("normal").remove();
					$(elm).parent().parent().hide("slow").remove();
				}
			}
		});
	} else {
		return false;
	}
	return false;
}


function keyup(what, maxKeys) {
  var str = new String(what.value);
  var len = str.length;
  var showstr = '<span class="smallfont">'+len + ' characters of ' + maxKeys + ' entered</span>';
  if (len > maxKeys) {
	  showstr += '<br><span class="smallfont red">Some information will be lost, please revise your entry</span>';
  }
  
  div = $(what).next('div');
  $(div).html(showstr);
}

function clearField(elm, defaultval) {
	if(elm.value == defaultval) {
		elm.value = '';	
	}
}

function addToFavorite(elm, bid) {
	$("div.loading").text("Adding to your favourite list....").fadeIn("slow");
	$.ajax({
		type:"POST",
		url: "addtofavorite.php",
		data: 'action=add&bid='+bid,
		success: function($data){
			if($data == "success") {
				$("div.loading").text("Added to your favourite list....");
				$(elm).text("Added to your favorite list.").removeAttr("onclick");
				$("div.loading").fadeOut("slow");
			} else {
				$("div.loading").fadeOut("slow");	
				alert("Error on adding in your favorite list.");
			}
		}
	});
}


function removeFavorite(elm, fvid) {
	//alert($(elm).parent().parent().get(0).tagName);
	//return;
	if(confirm("Are you sure you want to remove this boat from your favorite list")) {
		$("div.loading").text("Removing boat from your favourite list").fadeIn("slow");
		$.ajax({
			type:"POST",
			url: "addtofavorite.php",
			data: 'action=remove&fvid='+fvid,
			success: function($data){
				if($data == "success") {
					$("div.loading").text("Removed from your favourite list");
					$(elm).parent().fadeOut("slow").remove();
					$("div.loading").fadeOut("slow");
				} else {
					$("div.loading").fadeOut("slow");
					alert("Error on removing from your favorite list.");
				}
			}
		});
	}
}

function email_to_friend(product_name, boatLink, userName, userEmail) {
  url =  'http://review.alchemydigitalmedia.com/index.php?q=email&product_name='+product_name+'&link='+boatLink+'&username='+userName+'&email='+userEmail+"&store_id=web-0001";
   window.open(encodeURI(url), 'EmailtoFriend', 'menubar=no,height=350,width=500,scrollbars=no');
   return false;
}

function openWndStat(bid) {
	var url = "boat_stat.php?bid="+bid;
	window.open(encodeURI(url), 'BoatStat', 'menubar=no,height=620,width=500,scrollbars=yes');
}

function showPopupFeatures() {
   var url =  'pricing-popup.php';
   window.open(encodeURI(url), 'ViewPackageFeatures', 'menubar=no,height=600,width=535,scrollbars=yes');
   return false;
}

function openSendMessageWindow(recName, to) {
	var url = "message_send.php?name="+ recName+"&to="+to;
	window.open(encodeURI(url), 'SendMessage', 'menubar=no,height=340,width=520,scrollbars=no');
}