function enlarge(pic,title,width,height)
{
	preview = window.open("", title, "resizable=yes,toolbar=no,scrollbars=no,menubar=no,status=no,directories=no,width="+width+",height="+height+"");
	preview.document.write('<html><head><title>Picture<\/title><\/head>'+'<body onBlur="self.focus();" marginWidth="0" marginHeight="0" topmargin="0" leftmargin="0">'+'<center><img border="0" src="'+pic+'" width="'+width+'" height="'+height+'">'+'<\/center><\/body><\/html>');
	preview.document.close();
}

/**
 * This is the window.onload function, which fires when everything in the window has loaded
 */
$(window).load(function () {
	
	if(!$('#sb-container').length){
		Shadowbox.load();
	}
	
	window.onresize = function(){//This make the shadowbox overflow act correctly
		if ($('#sb-content.html').length) {
			setTimeout(function(){
			
				var contentPadding = $('#sb-content.html').outerHeight(true) - $('#sb-content.html').innerHeight();
				$('#sb-content.html').css('height', $('#sb-body.html').innerHeight() - contentPadding + 'px');
				
			}, 51);
		}
	}
	
	
});


/**
 * This is the jQuery document ready function, which fires as soon as the dom is ready for js, 
 * which is TYPICALLY just before the window.onload function
 */
$(function() {
	
	//	This is the shadowbox init function and the function for 
	if (Shadowbox) {
		Shadowbox.init({
			title: $(this).attr('title')
		});
	}
	
	if ($.fn.livequery) {
		$(".jqueryReplace, .clearDefault").livequery(function(){
			$(this).toggleValue();
		});
	} else if($(".jqueryReplace, .clearDefault").length) {
		$(".jqueryReplace, .clearDefault").toggleValue();
	}
});

$().ready(function() {

	var updateTitle = function(hash){$('.jqmAlertTitle h1').text($(hash.t).attr('title'));$(hash.w).show();};//()
	$('#glossaryDiv').jqm({ajax: '@href', trigger: 'a.glossaryTrigger', onShow: updateTitle, target: 'div.jqmAlertContent', ajaxText: '<p style="text-align:center">Please wait, loading content... <br /><img src="/media/pics/site/loading.gif" alt="loading" /></p>'});
	$('a.new-window').click(function(){
        window.open(this.href,this.title,'width=600,height=500,resize=true');
        return false;
    });
	$('a.new-window-scroll').click(function(){
        window.open(this.href,this.title,'width=620,height=600,resize=true,scrollbars=yes');
        return false;
	});
	$('a[rel*=lightbox]').lightBox(); // Select all links that contains lightbox in the attribute rel
	
	if($.fn.tabs){
		$('#tabs, .buynow-tabs > div').tabs();// Tabs
		
		$('#dialog_link, ul#icons li').hover(//hover states on the static widgets
			function() { $(this).addClass('ui-state-hover'); },
			function() { $(this).removeClass('ui-state-hover'); }
		);
	};
	
	if($.fn.datepicker){
		$.datepicker.setDefaults({showOn: 'both', buttonImageOnly: true, buttonImage: '/media/pics/cms/icon_calendar.gif', buttonText: 'Calendar'});
		$('.date-pick').datepicker({//single date
			onSelect: function() {
				$(this).change().blur(); /* Important for triggering jquery form validation on change */
			},
			dateFormat: 'dd/mm/yy'
		}).attr("readonly", "readonly"); 
		$('.future-date-pick').datepicker({//single date
			onSelect: function() {
				$(this).change().blur(); /* Important for triggering jquery form validation on change */
			},
			minDate:+1,
			dateFormat: 'dd/mm/yy'
		}).attr("readonly", "readonly"); 
		$(".range-date-pick").datepicker({ //date range
		    rangeSelect: true, 
		    showOn: "both",
			dateFormat: 'dd/mm/yy'
		}).attr("readonly", "readonly");
	}
	
	/*
	$("#SearchKeyword").focus(function(){
			if ($("#SearchKeyword").val() == 'Keyword or Part No ?'){
				$("#SearchKeyword").val("");
			}
		});
		$("#SearchKeyword").blur(function(){
			if ($("#SearchKeyword").val().length == 0){
				$("#SearchKeyword").val("Keyword or Part No ?");
			}
		});*/
	
	
	if ($.fn.stars) {
		$(".feedbackStars").stars();
	}
	
	if ($.fn.selectbox) {
		$('.dropdown').selectbox();
		$('.dropdownBanner').selectbox();
	}
	
	/*if ($.fn.tooltip) {
		$('.tooltip').tooltip({
			bodyHandler: function(){
				return $($(this).attr("href")).html();
			},
			track: false,
			delay: 2,
			showURL: false,
			opacity: 1,
			fixPNG: true,
			top: 0
		});
		
		$('.tooltip-left').tooltip({
			bodyHandler: function(){
				return $($(this).attr("href")).html();
			},
			track: false,
			delay: 2,
			showURL: false,
			opacity: 1,
			fixPNG: true,
			top: -15,
			left: -247
		});
	}*/
	
	//predictive test
	
	$("#SearchKeyword").autocomplete("/org/red5/ajax/suggestKeyword.cfm", {
		cacheLength: 500,
		selectFirst: 1,
		delay: 100,
		autoFill: false,
		max: 50,
		plusTop: 7,
		plusLeft: -110
	});
	
	// $("#SearchKeyword").result(function(event, data, formatted){
		// if (data) {
			// $("#SearchOfferID").val(data[1]);
		// }
	// });
	
	$("#carouselSearchKeyword").autocomplete("/org/red5/ajax/suggestKeyword.cfm", {
		cacheLength: 500,
		selectFirst: 1,
		delay: 100,
		autoFill: false,
		max: 50,
		plusTop: 7,
		plusLeft: -10
	});
	
	// $("#carouselSearchKeyword").result(function(event, data, formatted){
		// if (data) {
			// $("#SearchOfferID").val(data[1]);
		// }
	// });
	
	
	/*$("#redemptionHoldForm-div").livequery(function(){
			//$.removeData($('#redemptionHoldForm'),'validator');
			$.validator.addMethod("password", function(value, element, param){
				return this.optional(element) || (value.length > 5 && value.match(/[0-9]/) && value.match(/[a-zA-Z]/));
			}, jQuery.format("Please enter a combination of letters and digits. Minimum length is 6."));
			$("#redemptionHoldForm").validate({
				rules: {
					CompanyName: "required",
					Email: "required",
					claimQuantity: "required",
					Password: {
						password: true
					},
					ConfirmPassword: {
						equalTo: "#Password"
					}
				},
				messages: {
					Email: "Please enter a valid email address",
					ConfirmPassword: "Please confirm your password"
				}
			});
	});*/
	
	if ($.validator) {
	
		$.validator.addMethod("password", function(value, element, param){
			if($(element).hasClass("dontValidatePassword")){
   				return true;
   			} else {
				return this.optional(element) || (value.length > 5 && value.match(/[0-9]/) && value.match(/[a-zA-Z]/));
			}
		}, jQuery.format("Please enter a combination of letters and digits. Minimum length is 6."));
		
		$("#BlogCommentForm").validate();
		$("#EmailFriendForm").validate();
		$("#ContactForm").validate();
		$("#CompetitionForm").validate();
		$("#UnsubscribeForm").validate();
		$("#SignUpForm").validate();
		$("#LostPassword").validate();
		$("#MyCompanyDetails").validate();
		$("#MyOfferForm").validate();
		$("#OfferFeedbackForm").validate();
		$("#ClaimForm").validate();
		$("#ToolTipForm").validate();
		
		$("#redemptionHoldForm-div").livequery(function(){
			
			$("#redemptionHoldForm").validate({
				rules: {
					CompanyName: "required",
					Email: "required",
					claimQuantity: "required",
					Password: {
						password: true,
						required: true
					},
					ConfirmPassword: {
						equalTo: "#Password",
						required: true
					}
				},
				messages: {
					Email: "Please enter a valid email address",
					ConfirmPassword: "Please confirm your password"
				}
			});
		});
		
		$("#UpdateDetailsForm").validate({
			rules: {
				Password: {
					password: true
				},
				ConfirmPassword: {
					equalTo: "#Password"
				}
			},
			messages: {
				ConfirmPassword: "Please confirm your password"
			}
		});
		$("#smCalculatorForm").validate({
			rules: {
				machineQTY: {
					required: true,
					number: true,
					range: [1, 50]
				}
			}
		});
		$("#OfferSummaryForm").validate({
			rules: {
				Terms: {
					required: true
				}
			}
		});
		$("#MemberDetailsForm").validate({
			rules: {
				Password: {
					password: true
				},
				ConfirmPassword: {
					equalTo: "#Password"
				}
			},
			messages: {
				ConfirmPassword: "Please confirm your password"
			}
		});
		$("#SubscribeForm").validate({
			rules: {
				Password: {
					password: true
				},
				ConfirmPassword: {
					equalTo: "#Password"
				}
			},
			messages: {
				ConfirmPassword: "Please confirm your password"
			}
		});
		$("#MyCompanyDetails").validate();
		
	}
	
	$("#downloadToExcel").click(function(){
		$("#Export").val(1);
		$("#" +$(this).parents('form').attr('id')).submit();
	});
	$(".xButton").click(function(){
		$("#Export").val(0);
	});
	$("#downloadToExcelMemberLoginReport").click(function(){
		$("#ExportMemberLoginReport").val(1);
		$("#" +$(this).parents('form').attr('id')).submit();
	});
	$(".xButton").click(function(){
		$("#ExportMemberLoginReport").val(0);
	});	
	$("#Country").change(function(){
		var selectedItem = $("#Country").attr("value");
		$('#OtherState').css("display","none");
		CountryID = selectedItem;
		$("#State").removeOption(/./);
		$.AjaxCFC({
			url: "/org/red5/ajax/geoCode.cfc",
			method: "getState",
			blockMessage: "Fetching States....",
			data: {"CountryID":selectedItem},
				success: function(r) {
					if(r.recordcount == 0){
						$('#State').addOption(0,'Other State',false);
						$('#OtherState').css("display","");
					}else{
						$('#State').addOption(0,'Select State',false);
					}
					for(var i = 0; i < r.recordcount; i++){
						$('#State').addOption(r.data.stateid[i],r.data.statename[i],false);
					}
					//sDumper(r.data);
				}
		});
	});
});

//check and uncheck checkboxes on a form
// onClick="checkAll(document.myform.list)
// onClick="uncheckAll(document.myform.list)"
function checkAll(field)
{
	if(field.length > 1){
		for (i = 0; i < field.length; i++)
			field[i].checked = true ;
	}else{
		field.checked = true ;		
	}
}

function uncheckAll(field)
{
if(field.length > 1){
		for (i = 0; i < field.length; i++)
			field[i].checked = false ;
	}else{
		field.checked = false ;		
	}
}
function showHide(item){
	itemID = document.getElementById(item);
	if(itemID.style.display == ''){
		itemID.style.display = 'none'
	}else{
		itemID.style.display = ''
	}
}

function popUp_help(url) {

if (document.all) {var xMax = screen.width, yMax = screen.height} 
else if (document.layers) {var xMax = window.outerWidth, yMax = window.outerHeight} 
else {var xMax = 640, yMax=480}; var xOffset = (xMax - 670)/2, yOffset = (yMax - 650)/2; 

sealWin=window.open(url,"",'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=0,width=700,height=500,screenX='+xOffset+',screenY='+yOffset+',top='+yOffset+',left='+xOffset+'');
self.name = "";
}

var popupfeatures = "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes";
function popUp(myurl) {var win = open(myurl,'popupwindow' + Math.floor(Math.random() * 100),popupfeatures + ',width=900,height=500');win.focus();}

function popupSized(myurl,height,width) {var win = open(myurl,'popupwindow',popupfeatures + ',width=' + width + ',height=' + height);win.focus();}

var counter = 0;
function count() 
{
	counter++;
	if(counter > 1) 
	{ 
		return false;
	}
	return true;
}
function ResetCounter() {
	counter = 0;
}
window.onunload = ResetCounter;

//------------------------------- Test for alphanumeric ---------------------------------------//

function IsAlpha(CheckString)
{
	return CheckString.match(/^[a-z]+$/i);
}

function IsNumeric(CheckString)
{
	return CheckString.match(/^[0-9]+$/);
}

//------------------------------- Test for amounts ---------------------------------------//

function AmountIsNumeric(CheckString)
{
	return CheckString.match(/^(\d*\.)?\d+$/);
}

//------------------------------- Test for email ---------------------------------------//

function IsEmail(email) {
	return email.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/);
}


//------------------------------- Enlarge an image ---------------------------------------//

function enlarge(pic,title,width,height)
{
	
	if(typeof preview != 'undefined'){preview.close()};
	preview = window.open("", 'ImagePopup', "resizable=yes,toolbar=no,scrollbars=no,menubar=no,status=no,directories=no,width="+width+",height="+height+"");
	preview.document.write('<html><head><title>Picture<\/title><\/head>'+'<body onBlur="self.focus();" marginWidth="0" marginHeight="0" topmargin="0" leftmargin="0">'+'<center><img border="0" src="'+pic+'" width="'+width+'" height="'+height+'">'+'<\/center><\/body><\/html>');
	preview.document.close();
}
	

function Sanitise(StringToClean) {
	var CleanString = StringToClean;
	CleanString = CleanString.toLowerCase().replace(/[^a-z0-9]+/g, '-');
	CleanString = CleanString.replace(/^[\-]+/, '');
	CleanString = CleanString.replace(/[\-]+$/, '');
	CleanString = CleanString.slice(0, 80);
	return CleanString;
}

var TitleLastEdit = "";
var ForceFillClean = 0;
function FillClean(TitleField, TitleCleanField) {
	if(Sanitise(TitleLastEdit) == TitleCleanField.value || ForceFillClean) {
		TitleCleanField.value = Sanitise(TitleField.value);
		ForceFillClean = 0;
	};
	TitleLastEdit = TitleField.value;
}

function Ellip(s, len) {
	s = s.replace(/<\/?[a-z]+[^>]*>/g, "");
	if(s.length > len) {
		s = s.slice(0, len) + "...";
	}
	return s;
}
