var IMAGE_CONTAINER_W=228;
var IMAGE_CONTAINER_H=171;
 var editFlag=false;
var CJ_Image = {
	Calculate: function(options) {
		// declare some local variables
		var ratioX, ratioY, scale, newWidth, newHeight;
		// Check to make sure all the required variables were sent and pass validation
		if (typeof options.srcWidth !== "number" || typeof options.srcHeight !== "number" || typeof options.destWidth !== "number" || typeof options.destHeight !== "number" || typeof options.method !== "string") {
			return;
		}
		// Grab scale ratios
		ratioX = options.destWidth / options.srcWidth;
		ratioY = options.destHeight / options.srcHeight;
		// Determine which algorithm to use
		if (options.method === "fit") {
			scale = ratioX < ratioY ? ratioX: ratioY;
		} else if (options.method === "fill") {
			scale = ratioX > ratioY ? ratioX: ratioY;
		}
		// Set new dimensions
		newWidth = Math.round(options.srcWidth * scale, 10);
		newHeight = Math.round(options.srcHeight * scale, 10);
		// Return the new dimensions, plus the offsets, and if the destination box
		// is smaller or equal to the source image dimensions
		return {
			width: newWidth,
			height: newHeight,
			offset: {
				x: parseInt((options.destWidth - newWidth) / 2, 10),
				y: parseInt((options.destHeight - newHeight) / 2, 10)
			},
			fits: options.srcWidth >= options.destWidth && options.srcHeight >= options.destHeight ? true: false
		};
	}
};
function todayDate() {
	var days = new Array("Sunday","Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday");
	var d = new Date();
	return ("<strong>Today is "+ days[d.getDay()]+" "+ d.getDate() + "/"+ d.getMonth()+1 + "/" + d.getFullYear()+"</strong>");

}

function cutoffText(text, size) {
	var str=text;
	if(str.length > size) document.write(str.substring(0,size)+"...");
	else document.write(str);
}
//a function to limit characters in text area
function textCounter(field,cntfield,maxlimit) {
	var fieldValLength = SNG_checkLength(field.value);
	
	if (fieldValLength > maxlimit)  {
		field.value = field.value.substring(0, maxlimit);
		var msg = " can not be more than ";
		if(field.name == "eventName")
			SNG_alert(' \'Event Name\''+msg+'200 characters.');
		else if(field.name == "shortDescription")
			SNG_alert('\'Short Description\''+msg+'75 characters.');
		else if(field.name == "about")
			SNG_alert(' \'About You\''+msg+'1000 characters.');
		else if(field.name == "descp")
			SNG_alert(' \'Event Description\''+msg+'4000 characters.');	
		else if(field.name == "category")
			SNG_alert(' \'Event Category\''+msg+'200 characters.');	
		else if(field.name == "tags")
			SNG_alert(' \'Event Tags\''+msg+'200 characters.');	
		else if(field.name == "fullPrice")
			SNG_alert(' \'Full Price\''+msg+'100 digits.');	
		else if(field.name == "fullPriceNotes")
			SNG_alert(' \'Full Price Notes\''+msg+'500 digits.');	
		else if(field.name == "child")
			SNG_alert(' \'Child Price\''+msg+'100 digits.');	
		else if(field.name == "childNotes")
			SNG_alert(' \'Child Price Notes\''+msg+'500 digits.');	
		else if(field.name == "familyPrice")
			SNG_alert(' \'Family Price\''+msg+'100 digits.');	
		else if(field.name == "familyPriceNotes")
			SNG_alert(' \'Family Price Notes\''+msg+'500 digits.');	
		else if(field.name == "memFriPrice")
			SNG_alert(' \'Members/Friends Price\''+msg+'100 digits.');	
		else if(field.name == "memFriPriceNotes")
			SNG_alert(' \'Members/Friends Price Notes\''+msg+'500 digits.');		
		else if(field.name == "concession")
			SNG_alert(' \'Concession\''+msg+'100 digits.');	
		else if(field.name == "concessionNotes")
			SNG_alert(' \'Concession Notes\''+msg+'500 digits.');	
		else if(field.name == "seniorCitizen")
			SNG_alert(' \'Senior Citizen Prize\''+msg+'100 digits.');	
		else if(field.name == "seniorCitizenNotes")
			SNG_alert(' \'Senior Citizen Price Notes\''+msg+'500 digits.');	
		else if(field.name == "groupPrice")
			SNG_alert(' \'Group Price\''+msg+'100 digits.');	
		else if(field.name == "groupPriceNotes")
			SNG_alert(' \'Group Price Notes\''+msg+'500 digits.');		
		//Venue	
		else if(field.name == "name")
			SNG_alert(' \'Venue Name\''+msg+'200 characters.');	
		else if(field.name == "description")
			SNG_alert(' \'Venue Description\''+msg+'4000 characters.');	
		else if(field.name == "usefulInfo")
			SNG_alert(' \'Useful Information\''+msg+'1000 characters.');			
		else if(field.name == "venueCategory")
			SNG_alert(' \'Venue Category\''+msg+'200 characters.');	
		else if(field.name == "venueTag")
			SNG_alert(' \'Tags\''+msg+'200 characters.');		
		else if(field.name == "address1")
			SNG_alert(' \'Address\''+msg+'200 characters.');	
		else if(field.name == "townCity")
			SNG_alert(' \'Town City\''+msg+'100 characters.');		
		else if(field.name == "postcode")
			SNG_alert(' \'Post Code\''+msg+'10 characters.');	
		else if(field.name == "timeNotes" || field.name == "timingNotes")
			SNG_alert(' \'Timing Notes\''+msg+'1000 characters.');		
		else if(field.name == "webAddress")
			SNG_alert(' \'Web Address\''+msg+'500 characters.');		
		else if(field.name == "email")
			SNG_alert(' \'Email\''+msg+'300 characters.');		
		else if(field.name == "enquiresPhNum")
			SNG_alert(' \'\Enquires Phone No.\''+msg+'30 characters.');			
	}
	
}


function findPos(obj) {
	var curleft = curtop = 0;
    if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	} else {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
	}
	return [curleft,curtop];
}

function showLoginTableEarnPound(obj){
	if(_$id('isUserLogged') && _$id('isUserLogged').value == 'Yes' )  {  
		var pos = findPos(obj);
		_$id('mainDiv_earnpound').style.left = pos[0] - 200 +'px'; 
		_$id('mainDiv_earnpound').style.top =  pos[1] - 130 +'px';
		showDivs('tbl_login_er');
       return;
	}else {
		var cntx = document.getElementById('cntx');
		if(cntx == null) cntx = "";
		else cntx = cntx.value;
		window.location = cntx;
	}
	
}


function showLoginTable(whichLink,obj) {  

	  if(null != whichLink) {
        $('#whichLink').val( whichLink);
      }
	  
	  if($('#isUserLogged').length > 0 && $('#isUserLogged').val() == 'Yes' )  {
	     checkLoginHandler("UserLogged");
	     return;
	  } else {
		  if($('#signInContainerDIV').length == 0){
			  SNG_loadContainer("SNG_showLoginCallBack()", 'signIn');
		  }else{
			  $('#signinlink').click();
		  }
	  }

}

function SNG_showLoginCallBack(){
	SNG_loadContainerSIUBindings();
	$('#signinlink').click();
}

function SNG_scrollToCenter(){
	
	x = getScrollWidth();
	y = getScrollHeight();
	_$id('mainDiv').style.left = x + 350 + 'px'; 
	_$id('mainDiv').style.top =  y + 200  + 'px';
}
function getScrollWidth()
{
   var w = window.pageXOffset ||
           document.body.scrollLeft ||
           document.documentElement.scrollLeft;
           
   return w ? w : 0;
}

function getScrollHeight()
{
   var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;
           
   return h ? h : 0;
}

function setDefaultValue(obj) {
		var val = trim(obj.value);
		if(val.length  == 0){
			obj.value=obj.defaultValue;
		}
}
function hideDivs(divName) {
	if(_$id(divName)) {
		 _$id(divName).style.display = 'none';
	}
}

function showDivs(divName) {
  if(_$id(divName)){
		 _$id(divName).style.display = '';
	}
}
function showRegistrationTable(divName) {
	hideDivs('tbl_login'); 
	showDivs(divName);
	if(document.getElementById('registration_form') != null) {
		document.getElementById('registration_form').nickName.value = '';
		document.getElementById('registration_form').email.value = '';
		document.getElementById('registration_form').reg_password.value = '';
		document.getElementById('registration_form').password1.value = '';
	}
}

function showResetLink() {
	showDivs('resetLink');
	hideDivs('forgetPasswordError');	
}

function showNickHelp(divName) {
	showDivs(divName);
}

function hideNickHelp(divName) {
	hideDivs(divName);
}
//End by Ammar

function goAddVenue( frm_name ){
var frmObj = _$id(frm_name);
if(frmObj != null)
	{
		frmObj.action="controller.web";
		frmObj.method.value="addVenueEvent";
		frmObj.submit();
	}

}
function o_nGoingChangeDates( ){
	var stats = _$id('ongoing').checked
	
		var _startD = _$id('startDate');
		var _endD = _$id('endDate');

if(stats)
	{
		
		if(_startD != null && _endD != null){
			
			var currDateObj = new Date();
			var yr = currDateObj.getFullYear();
			var stDate = "1/1/"+yr;
			var enDate ="31/12/"+yr;
			_startD.value = stDate;
			_endD.value = enDate;
		
		_startD.style.color = '#999999';
		_endD.style.color = '#999999'
		
		}else{
			alert("Date fields not found");
		}
		
	}else{
		
		_startD.style.color = '#000000';
		_startD.value="";
		_endD.style.color = '#000000';
		_endD.value="";

	}
}

function getQueryVariable(query, variable) {

var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
   return pair[1];
}
   return "0";
}
} 

function reportUnsuitable( )
{
	var formObj = _$id('unsuitable_form');
	if(formObj != null){
	var hlink = window.location.href;
	
		var qrStr = hlink.substr(0, hlink.indexOf('?'));
		
		var titleId = getQueryVariable(qrStr, "titleId");
		var venueId = getQueryVariable(qrStr, "venueId");
		
		hlink = qrStr + "?"  + getValue('eventURL'); // + "venueId=" +venueId+"&titleId=" + titleId;
        hlink = escape(hlink);
	
	
	var subject = "Report Unsuitable Information on Wozzon";
	var email = "feedback@wozzon.com" ;
	var body = "I would like to report Unsuitable information on Wozzon.com: " ;
	var message = " %0DType here any comments:%0D";	
	var comp ="mailto:"+email+"?subject="+subject+"&body="+ body + hlink+message;
	
	
			win = window.open(comp,'emailWindow');
			if (win && win.open &&!win.closed) win.close();
	}
}
/*function checkVenue(pageNo) {
	var _form = document.event_venue_main;
	var name = getValue('name');
	var town = getValue('townCity');
	if (name) name = trim(name);
	if (town.length<=0 || (town.indexOf("e.g. Manchester")!= -1)) town  = ''; else trim(town);
	
	if (( name.length <= 0 ) || (name.indexOf("e.g. Odeon")!= -1)) {
		errorMessages('errorDiv', 'Please fill in mandatory field(s) to continue');
		_$id('name').style.border = '1px solid #ff0000';
		_$id('venueName').style.color = '#ff0000';
	} else {
		showProgress();
		UserManager.checkVenue(name, town, pageNo, checkVenueHandler);
	}
}*/

function loginAjax(id) {
	
	SNG_loginAjax(id);
	
}
function logout(pageId) {
	var ctx = _$id('cntx').value;
	if(_$id('isUserLogged'))   {
		_$id('isUserLogged').value = 'No' ;
	}
	
	var objHomePageLogout  = _$id('#homePageLogout');
	var logoutGoHome = $('#onLogoutGoHome');
	if((logoutGoHome && logoutGoHome.length > 0) || (objHomePageLogout && objHomePageLogout.value=='true') )  {
		/*If User loged out from home page do no login on refersh page.*/
		window.location = ctx+"login.web?method=logout";
		
	} else {
		UserManager.logout(pageId, logoutHandler);
	}
	/*For Feature Banner*/
	setCookie("show_feature_banner", "", 0);
}
function logoutHandler(source) {/*Always reload the page when ever logout*/
		var url = document.location.href;
		var pointer =  url.indexOf("controller");
		var hashIndex = url.indexOf("#");
		var lengthUrl = url.length;
		if(url.charAt(lengthUrl) == "#") {
			url = url.substring(pointer,(lengthUrl-1));
		} else if(hashIndex > 0 ) {
		  url = url.substring(pointer,hashIndex);
		} else {
			url = url.substring(pointer,lengthUrl);
		}
		window.location = url;
}


/*function addVenue() {
	var town = getValue('townCity');
	var name = getValue('name')
	if (town.length<=0 || (town.indexOf("e.g. Manchester")!= -1)) _$id('townCity').value  = ''; 
	if (( name.length <= 0 ) || (name.indexOf("e.g. Odeon")!= -1)) _$id('name').value  = ''; 
	
	document.forms.event_venue_main.submit();
}*/
String.prototype.replaceAll = function(pcFrom, pcTo){

      var i = this.indexOf(pcFrom);

      var c = this;

      while (i > -1){

      c = c.replace(pcFrom, pcTo);
      i = c.indexOf(pcFrom);

      }

      return c;
      }


function validateNumber(inputVal) {
	inputVal = inputVal.replaceAll(' ', "");
	
	if (isNaN(inputVal)) {
		return false;
	} else {
		return true;
	}
}

/*function checkVenueDetail(){
	form = document.add_venue_form;
	var startDate = form.startTime.value;
 	var endDate =  form.endTime.value;
	var name = form.name.value;
	var town = form.townCity.value;	 
	var pnum = form.enquiresPhNum.value;
	var vDesc = form.description.value;
	var vCategory = form.venueCategory.value;
	var address = form.address1.value;
	var usefulInfo = form.usefulInfo.value;
	var tags = form.venueTag.value;
	var timingNotes = form.timeNotes.value;
	var email = form.email.value;
	
	if(name) name = trim(name);
    if(town) town  = trim(town);
	if(pnum) pnum  = trim(pnum);
	if(vDesc) vDesc = trim(vDesc);
    if(address) address  = trim(address);
	if(email) email = trim(email)
	
	
	if(timingNotes.indexOf("E.g. Mon-Sat 9AM-8PM, Sun 12AM-5PM; closed Bank holidays")!= -1) _$id('timeNotes').value  = '';
	if(tags.indexOf("E.g. modern art, live music, great food")!= -1) _$id('venueTag').value  = '';
	if(usefulInfo.indexOf("E.g. admission fee, members only, kids welcome, etc.")!= -1) _$id('usefulInfo').value  = '';
	
	if(name.length <= 0){
		displayErrorMessage("Please fill the venue name.");
		return false;
	}
	else if(vDesc.length <= 0){
		displayErrorMessage("Please fill the venue description.");
		return false;
	}
	else if( (vCategory.indexOf("Specify other category")!= -1) || vCategory.length <=0){
   	   displayErrorMessage("Please specify venue category");
	   return false;
    }
	else if(address.length <= 0){
		displayErrorMessage("Please fill in the address.");
		return false;
	}
	else if(town.length <= 0){
		displayErrorMessage("Please fill the town name.");
		return false;
	} 
	
	if(!compareGr8erDates(startDate,endDate)) {
			displayErrorMessage("Please provide a valid date range.");
			return false;
	} 
	else if(email.length > 0 && !checkEmail(email)){
			displayErrorMessage("Please provide valid email address.");
			return false;
	}
	else if(!(validateNumber(pnum))){
		displayErrorMessage("Phone number should be numeric.");
		return false;
	}
	else {		
		document.forms.add_venue_form.submit();
	}	
	
}

function editVenueForm(){
	document.venue_detail_form.method.value="editVenueForm";
	document.venue_detail_form.submit();
	}

function submitVenue(){
	document.forms.venue_detail_form.method.value="submitVenue";
	document.forms.venue_detail_form.submit();
	}
*/	

/*function addEvent(){
	document.forms.venue_detail_form.action="e_controller.web";
	document.forms.venue_detail_form.method.value="addEventForm";
	document.forms.venue_detail_form.submit();
	}*/
	

function login(){

 var email = document.forms.gdp_main_login.email.value; 
 if(trim(email).length == 0 ) {
   errorMessages("loginErrorDiv","Email address is required.");
 } else if(checkEmail(email)) {
	 document.forms.gdp_main_login.submit();
 }else{
    errorMessages("loginErrorDiv","Please enter valid email address.");
 }
}
function resetPass(){
 if(checkEmail(document.forms.login_form.email.value)) {
 	 document.forms.login_form.method.value="resetPass";
	 document.forms.login_form.submit();
		}else{
			errorMessages("loginErrorDiv","Please enter valid email address.");
		}
}

function doResetPass(){
	
	
	if(document.forms.login_form.login_password.value.length <=4 || (document.forms.login_form.login_password.value != document.forms.login_form.re_login_password.value )){
		
		if(document.forms.login_form.login_password.value.length <=4 ){
	errorMessages('loginErrorDiv', 'The password should be a minimum of 5 characters long.')
		}else if(document.forms.login_form.login_password.value != document.forms.login_form.re_login_password.value){
	errorMessages('loginErrorDiv', 'Passwords do not match.')		
		}
	}else{
 	 document.forms.login_form.method.value="doResetPass";
	 document.forms.login_form.submit();
	}
}


function registerNow() {
	    if(!checkEmail(document.forms.registration_form.email.value)){
	 		//displayErrorMessage("Please enter valid email.");		
			errorMessages(null,"Please enter valid email address.");	
		}else
		if(document.forms.registration_form.nickName == ""){
			errorMessages(null,"Enter nick name.");
		}else 
		if(document.forms.registration_form.password.value.length <5 ){
			errorMessages(null,"The password should be a minimum of 5 characters long.");
		}else
		if(document.forms.registration_form.password.value != document.forms.registration_form.password1.value){
			errorMessages(null,"Passwords do not match.");
		}
		else{
			document.forms.registration_form.submit();
		}
}

function registerEarnPound(){
	var userAge = "";
	var firstName = "";
	var lastName = "";
	var gender = "";
	var reviewRegion = "";
	var paypalEmail = "";

	UserManager.isEarnPoundReviewer(function(data){
		if(data=='notreviewer'){
			var div = "registerationError_er" ;
			
			firstName = document.getElementById('registration_form_er').firstName.value;
			lastName = document.getElementById('registration_form_er').lastName.value;
			userAge = document.getElementById('registration_form_er').age.value;
			gender = document.getElementById('registration_form_er').gender.value;
			reviewRegion = document.getElementById('registration_form_er').reviewRegion.value;
			paypalEmail = document.getElementById('registration_form_er').paypalEmail.value;
			termsAndConditions = document.getElementById('registration_form_er').termsAndConditionsReview;
			
			if(!(termsAndConditions!=null && termsAndConditions.checked)){
				displayMsg(div, "You must agree to our Terms & Conditions before you can Sign Up.");
			}else if(trim(firstName) == ""){
				displayMsg(div,"Enter first name.");
			}else if(trim(lastName) == ""){
				displayMsg(div,"Enter last name.");
			}else if(!checkEmail(paypalEmail)){
				displayMsg(div,"Enter PayPal Email address.");
			}else{
				displayMsg(div,"");
				UserManager.registerEarnByReview(firstName, lastName, gender, userAge, reviewRegion, paypalEmail, registerationEarnPoundHandler);
			}
		}else if(data!="" && data!='error'){
			div = "registerationError_er"
			displayMsg(div, "Hey " + data +"! You are already registered with this campaign as a local reviewer.");
		}else if(data=='error'){
			div = "registerationError_er"
			displayMsg(div,"Error.");
		}
		
		
	});
}

var user_nickName ="";
function registerNowAjax(id, promotionalReg) {
	var emailId = "";
	var nickName = "";
	var regPassword = "";
	var termsAndConditions = "";
	
	var div = "";
	if(id == '1' ) {
		div = "registerationError" ;
		document.getElementById('registration_form').identity.value = '1';
		emailId = document.getElementById('registration_form').email.value;
		nickName = document.getElementById('registration_form').nickName.value;
		regPassword = document.getElementById('registration_form').password.value;
		retypePass = document.getElementById('registration_form').password1.value;
		termsAndConditions = document.getElementById('registration_form').termsAndConditions;
	}
	
	if(!checkEmail(emailId)){
			displayMsg(div,"Please enter valid email address.");	
		}else
		if(!(termsAndConditions!=null && termsAndConditions.checked)){
			displayMsg(div, "You must agree to our Terms & Conditions before you can Sign Up.");
		}else if("" == nickName || nickName.length == 0){
			displayMsg(div,"Enter nick name.");
		}else if(SNG_checkNickname(nickName)){
			displayMsg(div, NICK_NAME_INVALID_CHAR);
		}else 
		if(regPassword.length <5 ){
			displayMsg(div,"The password must be at least 5 characters long.");
		}else
		if(regPassword != retypePass){
			displayMsg(div,"The entered passwords do not match.");
		}else{
			var isRemember = "N";
			var remFlag = false;

			var reg_form_chkbox = document.getElementById('registration_form').chk_rememberMe;
			
			if(reg_form_chkbox != null && reg_form_chkbox.checked)
			isRemember = "Y";
			
			var productServicesChkBox = document.getElementById('productServices');
			
			if(promotionalReg != null && productServicesChkBox && productServicesChkBox.checked){
			remFlag = true;
			}else{remFlag = false;}
			var regPg = document.getElementById('reg_page');
			if(regPg != null){
				regPg = regPg.value;
			}else{
				regPg='wozzon/default'
			}
			
			UserManager.register(remFlag, emailId, nickName, regPassword, isRemember, regPg, registerationHandler);
			
			user_nickName = nickName;
		}
}
/*function submitEvent(){
	   validateEventFormData(document.add_event_form);
}*/	
function addAnotherEvent(){
	
	var addAnotherObj = _$id('addAnotherEvent');
		addAnotherObj.value = 'true';
		document.add_event_form.submit();
	}	
		
/*function addVenue_Event(id){
	if(id > 0 ) {
	    document.forms['add_venue_event'].venueId.value=id;
    	document.forms['add_venue_event'].submit();
	}	else {
		document.add_event_form.action="v_controller.web";
		document.add_event_form.method.value="venueDetail";
		document.add_event_form.submit();
	}
}*/

function enterData(e) {
    if (Number(e) == 13) {
		checkVenue(0);
	} else {
		removeErrorState();
		_$id('btnCheckVenue').style.display = '';
   		_$id('btnAddNewVenue').style.display = 'none';
		_$id('venueslist').style.display = 'none';
		checkDisplayLink();
	}
}

/*function onEnterKeyLogin(e,id) {
	if(Number(e) == 13) {
		SNG_loginAjax(id);
	}
}*/

function checkDisplayLink(){
	var name = getValue('name');
	var town = getValue('townCity');

	if((name!= "") && (town!="" ) ){
		document.getElementById('bottom').style.display = ''; // Shaheer
		//document.getElementById('nlinked').style.display = 'none';
		//document.getElementById('linked').style.display = '';
		document.getElementById('venueslist').style.display = 'none';
	}else if((name != " e.g. Odeon") && (town != " e.g. Manchester")){
		document.getElementById('bottom').style.display = ''; // Shaheer
		//document.getElementById('nlinked').style.display = 'none';
		//document.getElementById('linked').style.display = '';
		document.getElementById('venueslist').style.display = 'none';
	}
	else{
		document.getElementById('bottom').style.display = ''; // Shaheer
		//document.getElementById('nlinked').style.display = '';
		//document.getElementById('linked').style.display = 'none';
		document.getElementById('venueslist').style.display = 'none';
		
		}
}

/*function checkVenueHandler(source) {
try{
	var obj =  _$id("venueslist");	

		document.getElementById('bottom').style.display = 'none'; // Shaheer		    
		document.getElementById('venueslist').style.display = '';
   
  if( source == "error" ) 
      displayErrorMessage("Error processing your request.");	
   else if( source == "logout")   
      displayErrorMessage("Your login session has expired");
   else if( source == "notfound")   
      displayErrorMessage("Your login session has expired");   
   else   {          
     obj.innerHTML = source;
   }
   _$id('btnCheckVenue').style.display = 'none';
   _$id('btnAddNewVenue').style.display = '';
   
}catch(error){
	   hideProgress();
	}finally{
		hideProgress();
	}
}*/

function checkVenueHandler(source) {
try{
	var obj =  _$id("venueslist");	

		document.getElementById('bottom').style.display = 'none'; // Shaheer		    
		document.getElementById('venueslist').style.display = '';
   
  if( source == "error" ) 
      displayErrorMessage("Error processing your request.");	
   else if( source == "logout")   
      displayErrorMessage("Your login session has expired");
   else if( source == "notfound")   
      displayErrorMessage("Your login session has expired");   
   else   {          
     obj.innerHTML = source;
   }
   _$id('btnCheckVenue').style.display = 'none';
   _$id('btnAddNewVenue').style.display = '';
   
}catch(error){
	   hideProgress();
	}finally{
		hideProgress();
	}
}

function checkUserSyncAccount() {
	UserManager.checkUserSyncAccount(checkUserSyncAccountHandler);
}

function checkUserSyncAccountHandler(source) {
	var syncAccount = _$id('syncAccount');
	
	try {
		if (source == "error") {
			syncAccount.style.display = 'none';
		} else if (source == "alreadySync") {
			syncAccount.style.display = 'none';
		} else if (source == "notSync") {
			/*For reverting Feature Banner
			syncAccount.style.display = '';
			*/
			/* For Feature Banner*/
			if(_$id('hasToggled').value=='0'){
				_$id('hasToggled').value = "1";
				if(_$id('removeSyncPanel').value!="true"){
					syncAccount.style.display = '';
					toggleFeatureBanner();
				}else{
					syncAccount.style.display = 'none';
				}
			}			 
			hideShowFeatureBanner();
			/*For Feature Banner-End*/
		} else if (source == "invalid") {
			syncAccount.style.display = 'none';
		}
	} catch(err) {
	}
}
/* For Feature Banner*/
function hideShowFeatureBanner(){
	
	var syncAccount = _$id('syncAccount');
	var featureBanner = _$id('featureBanner');
	if(syncAccount.style.display == 'none'){
		featureBanner.style.display = '';
	}else{
		featureBanner.style.display = 'none';
	}
}

function toggleFeatureBanner(){
	var featureBannerVal = getCookie("show_feature_banner");
	var syncAccount = _$id('syncAccount');
	if(featureBannerVal=='0'){
		setCookie("show_feature_banner", "1", 1);
		syncAccount.style.display = 'none';
	}else{
		setCookie("show_feature_banner", "0", 1);
		syncAccount.style.display = '';
	}
}
/* For Feature Banner-End*/
function checkLoginHandler(source) {
	
	SNG_checkLoginHandler(source);

}

function registerationHandler(source) {
	var obj = _$id("registerationError");
	var div = "";
	div = "registerationError";	
	showDivs(div);	
	if( source == "1" ) displayMsg(div,"This email address has already been taken");
	else if(source == "2")   displayMsg(div,"Nickname already in use, please select another Nickname");
	else if( source == "3") displayMsg(div,"Error registering user");
	else if(source == "4")	displayMsg(div,"Please enter nick name.");
    else if(source == "5" ) displayMsg(div,"Please enter password.");
    else if(source == "6" ) displayMsg(div,"Please enter  email address.");

    else if(source == "Registered" || source == "ReRegistered")  {		
			
			//checkRemember('registration_form'); // if remmeber me checked save username
			 //var productServicesChkBox = _$id('productServices');
			// if comming from comptetion registeration page
 	 		
			   //removeUserInfo() ;
			   var submitForm = document.getElementById('compete_form');
			   if(submitForm != null){
				   checkRemember('registration_form'); // if remmeber me checked save username
				   submitForm.submit();
				   return ;
			   }
				
	  		
	  	hideDivs('tbl_registration');			
		var isreviewEvent = _$id('isReviewEvent')
		var isreview =_$id('isReview')
				
		if( !( (isreview && isreview.value == "Yes") ||  (isreviewEvent && isreviewEvent.value == "Yes") || 
					  ( _$id('whichLink').value == "showSubmitChanges" ) )  ) {		
		   SNG_messagePopup('registerationSuccess');	 		 
		}
		 checkLoginHandler(user_nickName);
	 } else  {          
	  	obj.innerHTML = source;
	}
}

function registerationEarnPoundHandler(source){
	
	var obj = _$id("registerationError_er");
	var div = "";
	div = "registerationError_er";	
	showDivs(div);	
	if(source == "7" ) displayMsg(div,"Please enter First Name.");
	else if(source == "8" ) displayMsg(div,"Please enter Last Name.");
	else if(source == "9" ) displayMsg(div,"Please enter PayPal Email.");
	else if(source == "10" ) displayMsg(div,"There is already another user associated with the Paypal email address you have specified.");
	else if(source == "Registered")  {		
	  	showDivs('tbl_regSuccess'); 
	 } else  {          
	  	obj.innerHTML = source;
	}
}

function showRegistrationPage(){
	
	isEarnPoundReviewer();
}
function isEarnPoundReviewer(){
	UserManager.isEarnPoundReviewer(isERReviewerHandler);
}

function isERReviewerHandler(data){
	var div ;	
	
	if(data=='notreviewer'){
		var cntx = document.getElementById('cntx');
		 if(cntx == null) cntx = "";
		 else cntx = cntx.value;
		 window.location = cntx +'promotions/registration_earnpound';
	}else if(data!="" && data!='error'){
		div = "alreadyReviewerDiv"
		displayMsg(div, "Hey " + data +"! You are already registered with this campaign as a local reviewer.");
	}else if(data=='error'){
		div = "registerationError_er"
		displayMsg(div,"Error.");
	}
}

function setStartFrom(cal) {
	var date = cal.date;
	var time = date.getTime()       
	var field = document.getElementById("startDate");	
	var date2 = new Date(time);
	field.value = date2.print("%d/%m/%Y");
	_$id('endDate').value = field.value;
}

function setEndDate(cal) {
    var date = cal.date;
    var time = date.getTime()       
    var field = document.getElementById("endDate");
    var date2 = new Date(time);
	field.value = date2.print("%d/%m/%Y");        
}

/*function updateAdminFee(id){
    var val ='0';
	if(id == 1){
	    _$id('priceDiv').style.display='';
		_$id('otherPriceLink').style.display='';				
	}else if(id == 2){
    	_$id('priceDiv').style.display='none';
		_$id('otherPriceLink').style.display='none';
		_$id('otherPrice').style.display='none';
		
	} else {
    	_$id('priceDiv').style.display='none';    	
    	val ='';			
	}
	setValue('fullPrice',val);
	setValue('child',val);
	setValue('familyPrice',val);
	setValue('memFriPrice',val);
	setValue('concession',val);
	setValue('seniorCitizen',val);
	setValue('groupPrice',val);
	
}

function setValue(id,val)
{
   var obj= _$id(id);
   if(obj)
   {
     obj.value=val;
   }
   else 
   {
     obj = _name(id);
     if(obj)
       obj.value=val;     
   }   
}*/


function loadSubCategory(){
	var obj   = _$id('categoryId');
    var index = obj.selectedIndex;
 	    id    =obj[index].value;

   if( id == "0" ) {   
     _$id('categoryId').selectedIndex=0;
	document.forms[0].subcategoryId.disabled=true; 
   } else {   
     UserManager.loadSubCategories(id, loadSubCatHandler);     
   }
}


function loadSubCatHandler(source){
     obj = _$id("sourceSubCatId");
     obj.innerHTML=source;
     obj.disabled=false;
     
}
function getDateObject(dateString,dateSeperator)
{
	//This function return a date object after accepting 
	//a date string ans dateseparator as arguments
	var curValue=dateString;
	var sepChar=dateSeperator;
	var curPos=0;
	var cDate,cMonth,cYear;

	//extract day portion
	curPos=dateString.indexOf(sepChar);
	cDate=dateString.substring(0,curPos);
	
	//extract month portion				
	endPos=dateString.indexOf(sepChar,curPos+1);			cMonth=dateString.substring(curPos+1,endPos);

	//extract year portion				
	curPos=endPos;
	endPos=curPos+5;			
	cYear=curValue.substring(curPos+1,endPos);
	
	//Create Date Object
	dtObject=new Date(cYear,cMonth-1,cDate);	
	return dtObject;
}
function parseTime(varTime){


}
function compareGr8erDates(val1, val2){

	if(val2 == "" ){
		return true;
	}
	var date1,date2;
	//date1 = getDateObject(val1,"/"); //As now the new date format has space, 
	//date2 = getDateObject(val2,"/"); //we can directly convert it to date obj

	date1 = new Date(val1)
	date2 = new Date(val2)
	
	if(date2 >= date1){
		return true;
	}else{
		return false;
	}
}
function validateFullPrice(valv){
	
	if(valv.indexOf("") != -1){
		valv = valv.replace("","");
		return isNumeric(valv)
	}else{
	return isNumeric(valv)
	}
	
}

	
	
function isDaySelected(){
	var is_selected=false;
		for(i = 0;i <= 6 ; i++){
			if(document.add_event_form.days[i].checked == true ){
				is_selected=true;
				}
		   }
	return is_selected;
	}

function checkDays(){
	var all_checked=true;	

	for(i = 0;i <= 6 ; i++){
		if(document.add_event_form.days[7].checked==true && document.add_event_form.days[i].checked  == false ){
			document.add_event_form.days[7].checked = false;
				}
		}

	for(i = 0;i <= 6 ; i++){
		if(document.add_event_form.days[i].checked == false ){
			all_checked=false;
				}
		   }
 	document.add_event_form.days[7].checked = all_checked;
}

function updateDays(){
	if(document.add_event_form.days[7].checked==true)
	for(i = 0;i <= 7 ; i++){
	    document.add_event_form.days[i].checked=true;
		}

}
function checkAllVenueDays(){
	//if(document.add_venue_form.days[7].checked==true)
	for(i = 0;i <= 6 ; i++){
	    document.add_venue_form.days[i].checked=true;
		}

}
function unCheckAllVenueDays(){
	//if(document.add_venue_form.days[7].checked==true)
	for(i = 0;i <= 6 ; i++){
	    document.add_venue_form.days[i].checked=false;
		}

}


function cancel(name){
   if(_$id(name)) {
	_$id(name).method.value="cancel";	
   } else {
      _$id("method").value="cancel";     
   }
   document.forms[name].submit();
}

function isNumeric(strString)
   //  check for valid numeric strings	
   {
   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 isValidTime(obj, skip)
   //  check for valid numeric strings	
   {
	var strString = obj.value;
   var strValidChars = "0123456789:AM PM am pm Unknown";
   var strChar;
   var blnResult = true;
	
   if(skip && (trim(strString).length <= 0 || strString == ' e.g. 9:00 AM')){
   
   obj.value = "";
   return 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 validatePostCode(strString) {
   var strValidChars = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
   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 validateTimeFormat(value, skip) {
	var flag = true;
	var hasMeridian = false;
	value = value.toUpperCase();
	
   var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [AP][M]?)?$/;
   
   if(value == "UNKNOWN" || value == "OPTIONAL" || value == "Unknown" || value == "Optional"){
		flag =  true;
	}
   else {
		   if (!re.test(value)) { flag = false; }
		   if (value.indexOf("AM") > 0) { hasMeridian = true; }
		   if (value.indexOf("PM") > 0) { hasMeridian = true; }
		   var values = value.split(":");
		   if (hasMeridian)
		   {
			  if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) )
				{
				  flag = false;
				 }
			}else{
			   flag = false;
		   }
		   
		   if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { flag =  false; }
		   if (values.length > 2) {
			  if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) { flag =  false; }
		   }
   
   }
   if(skip && trim(value).length <= 0 && !flag){
		flag = true;
	}
	
   return flag;
}

function dotimedrop(time){
var cal_time;
	if(time == "startTimeSelect"){
		cal_time = document.add_event_form.startTimeSelect[document.add_event_form.startTimeSelect.selectedIndex].value;
  	 	if(cal_time == 'All Day'){
		document.add_event_form.startTime.value='12:00 AM';	
		document.add_event_form.startTime.setAttribute('readonly','readonly');
		document.add_event_form.startTime.style.color = '#999999'

		document.add_event_form.endTime.value='12:00 AM';	
		document.add_event_form.endTime.setAttribute('readonly','readonly');
		document.add_event_form.endTime.style.color = '#999999'

		}else{
		document.add_event_form.startTime.value=cal_time;
		document.add_event_form.startTime.removeAttribute('readOnly');
		
		if(document.add_event_form.startTime.value != ' e.g. 9:00 AM'){
		document.add_event_form.startTime.style.color = '#000000'
		}
		
		document.add_event_form.endTime.removeAttribute('readOnly'); 
		
		if(document.add_event_form.endTime.value != ' Optional'){
		document.add_event_form.endTime.style.color = '#000000'
			}
		}

		
			 
  	 }else
	if(time == "endTimeSelect"){
		cal_time = document.add_event_form.endTimeSelect[document.add_event_form.endTimeSelect.selectedIndex].value;
	if(cal_time=='All Day')
		{
  	 	document.add_event_form.endTime.value= '12:00 AM';
		document.add_event_form.endTime.setAttribute('readonly','readonly');
		document.add_event_form.endTime.style.color = '#999999';

  	 	document.add_event_form.startTime.value= '12:00 AM';
		document.add_event_form.startTime.setAttribute('readonly','readonly');
		document.add_event_form.startTime.style.color = '#999999'

		}else{
  	 	document.add_event_form.endTime.value= cal_time;
		document.add_event_form.endTime.removeAttribute('readOnly');
		
		if(document.add_event_form.endTime.value != ' Optional'){
		document.add_event_form.endTime.style.color = '#000000'
		}
		
		document.add_event_form.startTime.removeAttribute('readOnly');
		if(document.add_event_form.startTime.value != ' e.g. 9:00 AM'){
		document.add_event_form.startTime.style.color = '#000000'
			}
		}
  	 }


}

/*function editEventForm() {

  document.add_event_form.method.value = "editEvent";
  document.add_event_form.submit();
}*/

function submitEventForm() {
   document.add_event_form.submit();
}

function addEventPriceValidator(strString)
   //  check for valid numeric strings	
   {
   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;  i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         break;
         }
      }
   return blnResult;
   }
   
   
function writeTimePeriod(_form){  
    var today = new Date();
    var day   = today.getDate();
    var month = today.getMonth() + 1;
    var year  = today.getYear();
 	if (year < 2000) year += 1900; 	
 	_form.gdp_whenfrom.value =  today.print("%d/%m/%Y");
	
	if(month == 12) {
	   month = 1 ;
	   year = year + 1  ;
	} else month = month + 1 ;
	
	var days = getDaysInMonth(month,year);
	if( days < day )  day = days;
	else if( day < 10 ) day = "0" + day;		
	if( month < 10 ) month = "0" + month;		
    _form.gdp_whento.value =  day + "/" + month+"/" + year; 
}


function killEnter(evt) {
	if(evt.keyCode == 13 || evt.which == 13) {
		//alert("ENTER");
		return false;
	}
return true;
}



//Add user Review on Venue Page (Ajax Based Functionality) 
var userVenueRating = 0;
function addReviewForVenue(id) {
   var comment =  _$id('userComment').value 
   var rating = _$id('rating').value;
   var termsAndConditions = _$id('termsAndConditionsReview');
   if(id != 0 && (comment == ' Add your comments here' || comment.length == 0)) {
	  SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
   } else if (comment.length > 1000) {
	   _$id('userComment').value = comment.substring(0,1000);
	   SNG_alert("Comment text can not exceed 1000 characters.");
   } else if (rating == 0) {
	   SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
   } else if (!(termsAndConditions!=null && termsAndConditions.checked) ) {
	   SNG_alert("You must accept our review terms & conditions before you can submit a review.");
   } else {
	  UserManager.addReviewVenue(id, comment, rating, addReviewVenueHandler);
	  userVenueRating = parseInt(rating);
   }
}


function addReviewVenueHandler(source) {
   var obj= _$id('showcomments');
   var hide= _$id('hideComments');
   var rate_this_venue = document.getElementById('rate_this_venue');
	
   if( source == "error" ) 
	   SNG_alert("Error processing your request.");	
   else if( source == "logout")  {
	   if(_$id('reviewMain') != null) {  
			showLoginTable('SubmitRating',_$id('reviewMain'));
			return;
		}		
   } 
   else {
	 if(source == "AlreadyReviewed" ) {
		 SNG_alert("You have already reviewed this venue.");

	    SNG_showCommentArea(false);
	    SNG_showAllReviews();
	   return;
   	 } 
   	 
     obj.innerHTML = source;	 
     SNG_showCommentArea(false);
     _$id('userComment').value ='' ;
     obj.style.display = '';
     var allComments = _$id('showAllComments');
     if(allComments) {
        hide.style.display = '';
     }
     var  reviewArea = _$id('reviewarea');
     if(reviewArea) {
        reviewArea.style.display = '';     
     }
     var userCommentCount =_$id('userCommentCount').value;
	 var totalRating = _$id('totalRating').value  ;
	 totalRating = parseInt(userVenueRating) + parseInt(totalRating);
     userCommentCount = parseInt(userCommentCount) +  1;
	 _$id('userCommentCount').value = userCommentCount;
	 SNG_selstar(totalRating , userCommentCount, true);
     if(userCommentCount == 1 ) {
       _$id('averageReview').style.display = '';   
     }
     if(userCommentCount > 1){
			$('.SNG_edRatingText').html('ratings');
	 }else{
			 $('.SNG_edRatingText').html('rating');
	  }
	  $('#totalReview').html(userCommentCount);
	  $('#totalReview2').html('(' + userCommentCount  +  ')');
   }
}
//Scripts for Editing user reviews
var isVenueEditUser = false;
function SNG_edituserReview(userCommentId, isVenue) {
	$('#isEdit').val('Yes');
	if(userCommentId != null) {
		$('#userCommentId').val(userCommentId);
		isVenueEditUser = isVenue;
		UserManager.editUserReview(userCommentId, SNG_editUserReviewHandler);
	}
}

function SNG_editUserReviewHandler(source) {
	var cntx = document.getElementById('cntx');
	if(cntx!=null)cntx = cntx.value;
	
	if(null != source) {
		if(source == "NotFound") {
			SNG_alert("Error processing your request.");
			return false;
		} else if(source == "logout") {
			SNG_alert("Login session expired.");
			return false;
		}
		else {
		 
		 $('#userComment').show();
		 $('#userComment').val(source);		 
		 
		 $('#commentSumbit').hide();
		 $('#commentUpdate').show();
		 SNG_showCommentArea(true);
		 //$('#editUserReviewLink').hide();
		 //Star Reseting Functionality	 
			 var rateStar = _$id('rateStar');
			 var rating = parseInt(_$id('noOfStars').value);
			 var message;
			 var starHtml = '';
       var messages = ["", "Terrible", "Bad", "Just OK","Good","Excellent"];
       message = _$id('star0'+rating).title;
       //rateIt(rating);

		if(isVenueEditUser){
			rateIt(rating, true);
			for (curnum = 1; curnum <= 5; curnum++) {
				
				if (rating >= curnum)
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +', true)">' +
					'<img src="'+cntx+'SNG_images/star_green.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+', true);" onmouseout="SNG_selstarRate('+rating+', true);"/> </a>\r\n';
				 else
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +', true)">' +
					'<img src="'+cntx+'SNG_images/star_white.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+', true);" onmouseout="SNG_selstarRate('+rating+', true);"/> </a>\r\n';
			}
		
		}else{
			rateIt(rating);
			for (curnum = 1; curnum <= 5; curnum++) {
				
				if (rating >= curnum)
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +')">' +
					'<img src="'+cntx+'SNG_images/star_yellow.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+');" onmouseout="SNG_selstarRate('+rating+');"/> </a>\r\n';
				 else
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +')">' +
					'<img src="'+cntx+'SNG_images/star_white.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+');" onmouseout="SNG_selstarRate('+rating+');"/> </a>\r\n';
			}
		}

		_$id('userComment').focus();
        rateStar.innerHTML = starHtml;
			
			//_$id('rateMessage').innerHTML = 'Terrible&#0133;<img src="'+cntx+'images/spacer.gif" alt="" width="40" height="15" />&#0133;Excellent';
			//_$id('rateMessage').style.color='#999999';
		}
	} 
	
	isVenueEditUser = false;
}

//End Of Scripts for Editing user Reviews
//End of 'Add User Reviews on Venue Page.

//Script for Pagination of Venues. [By Ammar ]

function getVenueNextPage(pageNo) {
	UserManager.getVenueNextPage(pageNo, checkVenueHandler);
}

//End of Scripts for Pagination of Venues 


//For Add Venue Submission (Scripts From Shaheer, integrated by Ammar) \
// Shaheer
function openAddTimingsArea() {
	document.getElementById("openDate").style.display = '';
	document.getElementById("openDay").style.display = '';
	document.getElementById("timingNotes").style.display = '';
	document.getElementById("addOpeneingTimes").style.display = 'none';
	_$id('addTimings').value = 'Yes';
	_$id('openDates').checked = true;
	_$id('daysOpen').checked = true;
	setAllYear('startTime', 'endTime'); //Setting Date 
	checkAllVenueDays(); //Setting all days of week
}

function closeAddTimingsArea() {
	document.getElementById("openDate").style.display = 'none';
	document.getElementById("openDay").style.display = 'none';
	document.getElementById("timingNotes").style.display = 'none';
	document.getElementById("addOpeneingTimes").style.display = '';
	_$id('chooseDate').style.display = '';
	_$id('showDay').style.display = 'none';
	_$id('showDate').style.display = 'none';
	_$id('addTimings').value = 'No';
}

function getVanueCategory(value) {
	if (value == "Other")
		document.getElementById("specifyVenueCategory").style.display = '';
	else
		document.getElementById("specifyVenueCategory").style.display = 'none';
}

function popupCalendar(obj) {
	var openDateFrom = new Date();  
	 var opentDateTo = new Date();
	 //opentDateTo.setMonth(openDateFrom.getMonth()+1);
	 document.add_venue_form.startTime.value =  openDateFrom.print("%d/%m/%Y");   
	 document.add_venue_form.endTime.value =  opentDateTo.print("%d/%m/%Y");
	 document.getElementById(obj).onclick();	 
}

function setDateCriteria(inputVal) {
	if(inputVal != null){
		_$id('dateCriteria').value = inputVal;
	}
}
function setAllYear(objWhen, objTo) {
	var currDateObj = new Date();
	var yr = currDateObj.getFullYear();
	var stDate = "1/1/"+yr;
	var enDate ="31/12/"+yr;
	_$id(objWhen).value = stDate;
	_$id(objTo).value = enDate;
}
function venueEventValidation() {
	// TODO
}

/*//For Event Pagination
function showPagedEvents(pageNo) {
	var venueId = _$id('venueId').value
	UserManager.eventPager(pageNo,venueId, eventPagerHandler);
}

function eventPagerHandler(source) {
	var obj = _$id('eventPager');
	_$id('firstListOfEvents').style.display = 'none';
	obj.innerHTML = source;
	
}*/

/*function showShortEventDetail(titleId) { //For a short ajax based detail of event in an overlay.	
	if(document.add_event_form.quickAddEventId) {
		document.add_event_form.method.value="showEventDetail";
		document.add_event_form.titleId.value=titleId;
		document.add_event_form.submit();		
	}else {
		UserManager.showEventDetail(titleId, showEventDetailHandler);
	}
}


function showEventDetailHandler(source) {
	var obj = _$id('shortEventDetail');
	if(source == "error") {
		displayErrorMessage("Error processing your request.");
	} else {
		obj.style.display = '';
		obj.innerHTML = source;
	}
}*/

function closeEventDetailLayer(divId) {
	var obj = document.getElementById(divId);
	if(obj != null) 
		obj.style.display = 'none';
}						 
//End For Add Venue Submission 

//Get All counties

function getCounties(countryId) {
	UserManager.getCountiesByCountryId(countryId, getCountyHandler);
}

function getCountyHandler(source) {
	document.getElementById('u8_trf').innerHTML = source;
	/*var obj = _$id('countyDropDown');
	obj.innerHTML = source;
	obj.style.display = '';
	if(source == "Error")
		obj.style.display = 'none';*/
}

// Shaheer -- 2008 09 15

function showToolTip(obj) {
	obj = _$id(obj);
	var pos = findPos(obj);
	_$id('openLayer').style.left = pos[0]  + 20 + 'px'; 
	_$id('openLayer').style.top =  pos[1] + 'px';
	_$id('openLayer').style.display = '';
	_$id('openLayer').style.position = 'absolute';
}

function hideToolTip(obj) {
	_$id('openLayer').style.display = 'none';
}
function submitViaEnter(evt, id) {
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13) {
		if(id =='resetPass'){
			//calling ajax submit method.
			doResetPassAjax();
			return false;
		}
		else if(id =='search'){
			//calling ajax submit method.
			lowerSearchEvents();
			//return false;
		}else if(id == 'LocationSpecified'){
			defaultLocationSpecified();
			return false;
		}
    }
	return true;
}
//End get All Counties

function saveGeoLocation(){
	var lat = _$id('latitude').value;
	var lng = _$id('longitude').value;
	UserManager.saveGeoLocation(lat, lng, saveGeoLocationHandler);
}
function saveGeoLocationHandler(source){
	if(source != "OK"){
		alert("Warning: Error in Processing GEO Location");
	}
}
function  showProgress(){
	var obj = document.getElementById('dv_progress')
	if(obj != null){
		obj.style.display='inline';
	}
}
function  hideProgress(){
	var obj = document.getElementById('dv_progress')
	if(obj != null){
		obj.style.display='none';
	}
}

function storeSearchLocation(searchLocation) {
	UserManager.storeSearchLocation(searchLocation, storeSearchLocationHandler);
}
function storeSearchLocationHandler(source) {
	if(source == "error") alert("Error strong location in session...");
}


String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
		return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
}
function openTitleGroup(obj, linkObj){
	obj.style.display='';
	linkObj.style.display='none';
}

var SEARCH_LOC_ALL_UK = 'United Kingdom';

function populateSearchLocationFromCookie(){
	var currLoc = getCookie("currentSearchLocation");
	var locObj = _$id('searchLocation');

	if(currLoc != ""){
		locObj.value = currLoc;
	}else {
		locObj.value = SEARCH_LOC_ALL_UK;
	}
}

function fetchSearchLocationFromCookie(){
	var currLoc = getCookie("currentSearchLocation");
	var locObj = _$id('searchLocation');

	if(currLoc != ""){
		return currLoc;
	}else {
		return SEARCH_LOC_ALL_UK;
	}
}
function backToSearch(){
	_$id('gdp_form').submit();
}
function uploadFiles() {
  var image = dwr.util.getValue('imageFile');
  UploadDownload.uploadFiles(image,function(data) {
    dwr.util.setValue('image', data);
  });
}
function finishProgress(){
	var pbt = _$id('progressBarText');
	if(pbt){
		pbt.innerHTML = 'upload progress: 100%';
	}
	var pbtc = _$id('progressBarBoxContent');
	if(pbtc){
		pbtc.style.width = parseInt(100 * 3.5) + 'px';
	}
}

function getCroppedImg(){
	SNG_closeFancyBox();
	var image2 = _$id('image2');
	if(image2 == null || image2.value == ''){
		return;
	}
	image2  = image2.value;
	
	var iPath =  '/venueImages/images/'+ image2 + '?state='+new Date().getTime();
	showDivs('div_venue_img')
	hideDivs('div_upload')
	hideDivs('div_crop')
	showDivs('img_options')
	var objImg = _$id('venue_img');
	objImg.src=iPath;
	objImg.style.width='';
	objImg.style.height='';
	objImg.style.display='';
	//$('.SNG_edNoImage').hide();
	$('.SNG_edImgCont').removeClass('SNG_edImgContNoImg');
	showControls(false);
}


function resetProgressBar(){
	_$id('progressBar').style.display='none';
	_$id('progressBarBoxContent').style.width='0px';
	_$id('uploadbutton').disabled = false;
    _$id('file1').disabled = false;
    hideFileSection();
	_$id('frm_upload').reset();
	
}
function hideCropDiv() {
	
	if(qaImage) {
		qaImage = false;		
		hideDivs('div_crop');
	    divCrop = _$id('crop_div'); 
	    deleteNodes(divCrop);
	    createCropElement(divCrop);
	    if(_$id('uploadImage')) _$id('uploadImage').disabled = false;
	} else {
		if(editFlag){
			editFlag= false;
			_$id('div_crop').style.display='none';
		}else{
			resetProgressBar();
			hideDivs('div_crop');
			var divCrop = _$id('crop_div');
			deleteNodes(divCrop);
			createCropElement(divCrop);
			clearSession(_$id('image1').value, _$id('image2').value);
			hideFileSection();
			
			if(_$id('isEventSubmission').value=="true"){
				showDivs('upload_link');
			}else{
				if(imgs && imgs.length == 0){
					showDivs('upload_link');
				}	
			}
		}
	}
	
	if(!qaImagecropped) {
    	if(_$id('uploadImage'))
     	   _$id('uploadImage').disabled = false;
    }
	
}
function backToUpload(){
	if(qaImage) {
		qaImage = false;		
		hideDivs('div_crop');
	    divCrop = _$id('crop_div'); 
	    deleteNodes(divCrop);
	    createCropElement(divCrop);
		return false;
	}
	
	if(editFlag){
		editFlag= false;
		_$id('div_crop').style.display='none';
	}else{
	resetProgressBar();
	var divCrop = _$id('crop_div');
	deleteNodes(divCrop);
	createCropElement(divCrop);
	clearSession(_$id('image1').value, _$id('image2').value);
	hideFileSection();
	SNG_showUploadDlg();
	}
	
	
}

function deleteNodes(cell)
{
	if ( cell.hasChildNodes() )
	{
    	while ( cell.childNodes.length >= 1 )
    	{
        cell.removeChild( cell.firstChild );      
    	}
	}

}
function createCropElement(parent){
var newNode = document.createElement("img");
newNode.id="cropbox";
newNode.name="cropbox";
newNode.src='';
parent.appendChild(newNode);
}
function SNG_showUploadDlg(){
	
	editFlag= false;
	resetProgressBar();
	//$('#upload_link').hide();
	//if($('.beFirstToUpload').length > 0){$('.beFirstToUpload').hide();}
	
	//$('#fileUploadError').html('');
	if($('#uploadImage').length > 0) _$id('uploadImage').disabled = true;
	if($('#report').length > 0)
		$('#report').hide();
	$('#div_crop').hide();
	$('#div_upload').show();
	
	divCrop = _$id('crop_div'); 
	$('#file1').val('');
    deleteNodes(divCrop);
    createCropElement(divCrop);
    if(imgs != undefined && imgs!=null && imgs.length>0){
	    imgs[0].isOld="true";
		showImage(0);
    }
}
function clearSessionMoreImage(){
	   	clearSession(_$id('image1').value, _$id('image2').value);
	    document.getElementById('image1').value='';
	    document.getElementById('image2').value='';	
	
} 

var qaImage = false;
var qaImagecropped = false;
function getQuickAddToCrop(imageName,width,height){	 
	 _$id('image1').value = imageName
	 _$id('imageFileName').value=imageName;
	 var objCropBox = parent.document.getElementById('cropbox');
	 objCropBox.style.width=width + 'px'
	 objCropBox.style.height=height + 'px'
	 qaImage = true;
	 getImgToCrop();
	 _$id('image1').value = "";
}

function getImgToCrop(){
	finishProgress();
	var source = ""
	if(_$id('image1'))
		source = _$id('image1').value;
	
	if(source != ""){		
		var iPath = source;
		var imgName = "";
		if(iPath == null || iPath == ""){
			SNG_alert('error getting name');
			return;
		}
		imgName = iPath;
		iPath =  '/venueImages/images/'+ iPath;
		_$id('div_upload').style.display='none';
		//hideDivs('cancelUploadBtn');
		showDivs('backUploadBtn');
		_$id('div_crop').style.display='';
		
		if(_$id('cords') != null){
		_$id('cords').image.value=imgName;
		_$id('cords').x.value=0;
		_$id('cords').y.value=0;
		_$id('cords').w.value=0;
		_$id('cords').h.value=0;
		}
		var cropObj = _$id('cropbox');
		cropObj.src=iPath;
		cropObj.style.display='';
		_$id('div_img').style.display='';
		
		var rW = cropObj.width;
		var rH = cropObj.height;
		
		var cropperXOffset = (cropObj.width-IMAGE_CONTAINER_W)/2;
		var cropperYOffset = (cropObj.height-IMAGE_CONTAINER_H)/2;
		
		if(rW > IMAGE_CONTAINER_W){rW=IMAGE_CONTAINER_W;}
		if(rH > IMAGE_CONTAINER_H){rH = IMAGE_CONTAINER_H;}
			jQuery(function(){
				jQuery('#cropbox').Jcrop({
					aspectRatio: IMAGE_CONTAINER_W/IMAGE_CONTAINER_H,
					setSelect:   [ cropperXOffset, cropperYOffset, cropperXOffset+IMAGE_CONTAINER_W, cropperYOffset+IMAGE_CONTAINER_H ],
					onSelect: updateCoords
				});
			});
		SNG_resizeFancyBox();
	} 
	
	
}

function showDeleteImg(){
	if(!qaImage)
		showDivs('div_delete_pic')
	else {
		qaImage = false;
		hideDivs('div_crop');
	    divCrop = _$id('crop_div'); 
	    deleteNodes(divCrop);
	    createCropElement(divCrop);
	}
}

function deleteImg(image, page){	
	var del= confirm("Are you sure you want to delete this image?");
	if(del) {
		UserManager.delTempImages(image, page, delTempImageHandler);
	}

}

function delTempImageHandler(source) {
	var imgList = _$id('imageList');
	if(source == "error") {
		SNG_alert("error deleting image");
	}else if(source == "logout") {
		SNG_alert("Login session expired");
	}else if(source != "") {		
		if(imgList) {
			imgList.innerHTML = source;
		}
	}
}

function delOldImageHandler(source){
	if(source=="error"){
		SNG_alert("error deleting image");
	}else if(source=="logout"){
		SNG_alert("Login session expired");
	}else if(source==""){
		hideDivs('div_delete_pic');

		 var hlen = window.location.href.length;
		 if(window.location.href.substr(hlen-1,hlen)=="#"){
			 window.location.href = window.location.href.substr(0,hlen -1);
		 }else{
			 reloadWindow();
		 }
	}else{
		SNG_alert("error deleting image");
	}
	
}

function cancelShowDelete(){
	_$id('div_delete_pic').style.display='none';
}
function deleteImage(image1, image2){
	if(imgs!=null && imgs.length > 0&& imgs[imgCounter].isOld=="true"){ //If image is added prevsly.
		UserManager.deleteOldImage(imgs[imgCounter].imageId, delOldImageHandler);
	}else{//If image is just added (delete original and added image)
		UserManager.deleteImage(image1, image2, deleteImageHandler)
	}
}
function deleteImageHandler(source){
	if(source == null || source == "error"){
		SNG_alert("error deleting image");
	}

	hideDivs('div_delete_pic');
	 var hlen = window.location.href.length;
	 if(window.location.href.substr(hlen-1,hlen)=="#"){
		 window.location.href = window.location.href.substr(0,hlen -1 );
	 }else{
		 reloadWindow();
	 }
}
function reloadWindow(){
	window.location.href=window.location.href;
}
function acceptImg(entityId, image1, image2){
	UserManager.acceptImage(entityId, image1, image2, acceptImgHandler)
}
function acceptImgHandler(source){
	if(source == null || source =="error"){
		SNG_alert("error acception image");
		return;
	}
	SNG_closeFancyBox();
	//if(imgs.length == 1 && imgs[0].imageType == "lobbyImage"){
	//	imgs.pop();
	//}
	newValue = imgs.length;
	imgs.reverse();
	if(editFlag){
		newValue = newValue -1;
	}

	var infos = source.split("/");
	imgs[newValue] = new ImageInfo("/venueImages/images/"+infos[0],infos[2], infos[3], "1","false", infos[1], infos[4]);
	imgs.reverse();
	showImage(0);

}

function acceptImageOnClick(){
	acceptImg(_$id('entityID').value,_$id('image1').value, _$id('image2').value);
}

function editImg(image2){
	editFlag = true;
	UserManager.editImage(editFlag, image2, editImgHandler)
}
function editImgHandler(source){
	if(source == null || source == "error"){
		SNG_alert('error editimg image');
		return;
	}
	_$id('imageToDelete').value=_$id('image2').value;
	showDivs('div_crop');
	//showDivs('cancelUploadBtn');
	hideDivs('backUploadBtn');
	hideDivs('div_upload')
}
function reportUnsuitableImg(img, reportText, venueName, venueId, titleName, titleId){
	if(reportText.length == 0){
		SNG_alert('Please tell us why you find this picture inappropriate');
		return;
	}else if(reportText.length > 4000){
		SNG_alert('text should not bigger then 4000 characters');
		return;
	}
	UserManager.reportUnsuitableImgage(img.imageName, reportText, venueName, venueId, titleName, titleId, reportUnsuitableImgHandler)
}
function reportUnsuitableImgHandler(source){
	if(source == "error"){
		SNG_alert("Error processing your request");
	}
	hideDivs('div_report_pic');
	showDivConfirmReport(imgs[imgCounter].imageName);
}
function showDivReport(img){
	_$id('report_pic').src=img.imageName;
	_$id('img_report_txt').value='';
	_$id('div_report_pic').style.display='';
}

function showDivConfirmReport(img){
	_$id('div_confirm_report').style.display='';
	_$id('div_confirm_report_pic').src=img;
}
function hideDivConfirmReport(img){
	_$id('div_confirm_report').style.display='none';
	_$id('div_confirm_report_pic').src='';
}
function stopUpload(){
	window.clearTimeout(timeOut)
	cntx = document.getElementById('cntx');
	if(cntx != null) cntx = cntx.value;

	removeBack('target_upload', cntx + '/images/spacer.gif');
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		window.document.execCommand('Stop');
	}else{
		window.stop();
		
	}
	
}
function clearSession(image1, image2){
	if((image1!=null && image1!="") || 
			(image2!=null && image2!="")){
	
		UserManager.clearSession(image1, image2, clearSessionHandler)
	}
}
function clearSessionHandler(source){
	if(source == "error"){
		//alert(source);
	}
}
function resetUpload(){
	stopUpload();
	resetProgressBar();
}
function validateImage(image_file)
{
var extensions = new Array("jpg","jpeg","gif","png","bmp");
var image_length = image_file.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
	if(extensions[i] == final_ext)
	{
	return true;
	}
}
	return false;
}
function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function img_onload()
{
	var srcImg = _$id(imageIdent);
	var srcW = this.width;
	var srcH = this.height;
	var d_w=srcW;//IMAGE_CONTAINER_W;
	var d_h=srcH;//IMAGE_CONTAINER_H;
	var cnt_w=0,cnt_h=0;
	
	if(imageIdent == 'report_pic' || imageIdent == 'div_confirm_report_pic'){
		cnt_w=173;
		cnt_h=130;
	}else{//venue_img case
		cnt_w=IMAGE_CONTAINER_W;
		cnt_h=IMAGE_CONTAINER_H;
	}
		if(d_w > cnt_w){d_w=cnt_w;}
		if(d_h > cnt_h){d_h=cnt_h;}
	
		var thumbNail = CJ_Image.Calculate({
		srcWidth: srcW,
		srcHeight: srcH,
		destWidth:  d_w,
		destHeight: d_h,
		method: "fit"
	});

	var rW = thumbNail.width;
	var rH = thumbNail.height;
	srcImg.width=rW;
	srcImg.height=rH;
	if($('#venue_img ').length > 0){
		$('#venue_img ').vAlign();
	}
	
	if($('#userImage').length > 0 && imageIdent == 'userImage'){
		$('#userImage').vAlign();
	}
}
var imageIdent = '';
function scaleMyImage(srcImg, id) {
imageIdent = id;
var nwImg = new Image();
nwImg.onload = CreateDelegate(nwImg, img_onload);
nwImg.src = srcImg.src+'';

}

function getImgesList(){
	var cropDiv =_$id('div_crop');
	var divCrop = _$id('crop_div');
    if(cropDiv) {    	 
		 cropDiv.style.display='none';
		 _$id('div_upload').style.display='none';
		 _$id('upload_link').style.display='';
		 resetProgressBar();
		 deleteNodes(divCrop);
	   	 createCropElement(divCrop);		
		 hideFileSection();		 
	} 
   
    if(qaImage) {
    	qaImage = false;
    	qaImagecropped = true;
    	if(_$id('uploadImage'))
    	   _$id('uploadImage').disabled = true;
    }
    
    if(!qaImagecropped) {
    	if(_$id('uploadImage'))
     	   _$id('uploadImage').disabled = false;
    }
}
function hideFileSection(flag){
	if(flag){
	_$id('div_file').style.display='none';
	_$id('p_cert').style.display='none';
	//_$id('upload_statement').style.display='none';
	
	}else{
	_$id('div_file').style.display='';
	_$id('p_cert').style.display='';
	//_$id('upload_statement').style.display='';
	}
}
function showControls(flag){
	if(flag){		
		//showDivs('report');
		showDivs('nav_control');
	}else{

		if(imgs && imgs.length == 0){
			showDivs('tbl_venue_img');
		}
	}
}

function deleteQAVenue(venueId) {  
	var del= confirm("Are you sure you want to delete this venue?");
	if(!del) return false;
	var obj =  _$id("quickAdd_" + venueId);
    UserManager.delQuickAddVenue(venueId, 
    	function(source){
		 	if(source == "error") {
		 		errorMessages('errorDiv', 'Error deleting venue');
		 	}  else if(obj) {
	        	obj.style.display='none';
	        }
		}
    );
}

function deleteQAEvent(eventId) {   
	var del= confirm("Are you sure you want to delete this event?");
	if(!del) return false;
	var obj =  _$id("quickAdd_" + eventId);
	UserManager.delQuickAddEvent(eventId, 
    	function(source){
		 	if(source == "error") {
		 		errorMessages('errorDiv', 'Error deleting event');
		 	}  else if(obj) {
	        	obj.style.display='none';	        	
	        }
	
		}
	);
}

function removeBack(frame, URL) {
	
	var IFrameObj = document.getElementById(frame);
	if (IFrameObj.contentDocument) {
		// For NS6
		IFrameDoc = IFrameObj.contentDocument;
	} else if (IFrameObj.contentWindow) {
			//	For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	} else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	} else {
		return true;
	}

	IFrameDoc.location.replace(URL);
	return false;
}

function ImageInfo(imageName,nick,profileName, deleteable, isOld, imageId, uploadDate, imageType) {
	this.imageName=	imageName;
	this.nickName =	nick;
	this.profileName = profileName
	this.deleteable = deleteable;
	this.isOld = isOld;
	this.imageId = imageId;
	this.uploadDate = uploadDate;
	this.imageType = imageType;
}

function reportUnsuitableUserImg(imageLink, userProfilelink, reportText){
	if(reportText.length == 0){
		SNG_alert('Please tell us why you find this picture inappropriate');
		return;
	}else if(reportText.length > 4000){
		SNG_alert('text should not bigger then 4000 characters');
		return;
	}
	UserManager.reportUnsuitableUserImg(imageLink, userProfilelink, reportText,
			function(source) {
				$('#div_report_pic').hide();
				$('#div_confirm_report').show();	
			}			
	);
}

function reportUnsuitableProfile(userProfilelink, reportText){
	if(reportText.length == 0){
		SNG_alert('Please tell us why you find this profile inappropriate');
		return;
	}else if(reportText.length > 4000){
		SNG_alert('text should not bigger then 4000 characters');
		return;
	}
	UserManager.reportUnsuitableProfile(userProfilelink, reportText,
			function(source) {
				$('#report_profile').hide();
				$('#confirm_report').show();	
			}			
	);
}
