// JavaScript Document
/* Utility functions (SHARED) */
var prfSp=[];
var currPrf=0;
var getListed;
var site_owner;
var site_owner_email;
var currentLink;
var thumbsArr=[];
var picsArr=[];

function trim(stringToTrim) {
	if (stringToTrim) {
		return stringToTrim.replace(/^\s+|\s+$/g,"");
	} else return '';
};
function ltrim(stringToTrim) {
	if (stringToTrim) {
		return stringToTrim.replace(/^\s+/,"");
	} else return '';
};
function rtrim(stringToTrim) {
	if (stringToTrim) {
		return stringToTrim.replace(/\s+$/,"");
	} else return '';
};
function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
};
function isNumber(n) {
  	return !isNaN(parseFloat(n)) && isFinite(n);
};
function capitalizeMe(val) {
    //val = obj.value;
        newVal = '';
        val = val.split(' ');
        for(var c=0; c < val.length; c++) {
                newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + ' ';
        }
        //obj.value = newVal;
		return newVal;
};
function openW(mypage,myname,w,h,features) {
	if(screen.width){
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	}else{winl = 0;wint =0;}
	if (winl < 0) winl = 0;
	if (wint < 0) wint = 0;
	var settings = 'height=' + h + ',';
	settings += 'width=' + w + ',';
	settings += 'top=' + wint + ',';
	settings += 'left=' + winl + ',';
	settings += features;
	win = window.open(mypage,myname,settings);
	win.window.focus();
};
function js_array_to_php_array (a)
{
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(a[key]).length + ":\"" + String(a[key]) + "\";";
    }
    a_php = "a:" + total + ":{" + a_php + "}";
    return a_php;
};
function xmlDoc(xmlString) {
	if (window.DOMParser) {
	  	parser=new DOMParser();
	  	xmlDoc=parser.parseFromString(xmlString,"text/xml");
	  } else {
		// Internet Explorer
	  	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  	xmlDoc.async="false";
	  	xmlDoc.loadXML(xmlString);
	  } 
	  return xmlDoc;
	
};
function validateSearch() {
	$('#searchString').removeClass('errorClass');
	var str=$('#searchString').val();
	if ( trim(str) =='') {
		$('#searchString').addClass('errorClass');
		return false;
	}
	if (countyEventEntries) { $('#xmlEvents').val(saveCALEvents());	}
	return true;
};
function saveCALEvents() {
	var xml='<Root>';
	for (var i=0; i<countyEventEntries.length; i++) {
		var cEvent = new calEvent.Event();
		cEvent.setEvent(countyEventEntries[i]);
		xml += cEvent.getEventXML();
	}
	xml += '</Root>';
	return xml;
};
function setClassifiedsHover() {

	$('li.classifiedListing').hover(
	  function () {
		$(this).addClass("classifiedListingHover");
	  },
	  function () {
		$(this).removeClass("classifiedListingHover");
	  }
	); 

};
function quickLinkSponsor(prf) {
	// Verify this is a valid profile code
	var sponsorInfo=getSponsorInfoByProfile(prf);
	if (sponsorInfo) showSponsor(sponsorInfo.profile);
};
function showProfiledSponsors() {
	if (prfSp.length==0) { return true; }
	if (currPrf==prfSp.length) {currPrf=0;}
	var sp = prfSp[currPrf];
	var prfBox='<div class="ui-corner-all" id="prfBox" ><a onClick="quickLinkSponsor(\''+sp.profile+'\');"><img style="float:left" src="'+sp.image+'"><span id="prfName">'+sp.sponsor_name+'</span></a></div>';
	$('#iconBar td').first().html(prfBox);
	currPrf ++;
	setTimeout("rotateProfiles()",12000);
};
function rotateProfiles() {
	if (currPrf==prfSp.length) {currPrf=0;}
	var sp = prfSp[currPrf];
	var options = {};
	var prfBox='<a onClick="quickLinkSponsor(\''+sp.profile+'\');"><img style="float:left" src="'+sp.image+'"><span id="prfName">'+sp.sponsor_name+'</span></a></div>';
	$('#prfBox').hide('fade', options, 500, function() {
											  $('#prfBox').html(prfBox).show('fade',options,500);
						  					});
	currPrf ++;
	setTimeout("rotateProfiles()",12000);
};
function URLDecode(psEncodeString) {
  var lsRegExp = /\+/g;
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
};
function shareMe(nm,lnk,pic,capt,desc,msg) {
	 scroll(0,0);
	 FB.ui(
	   {
		 method: 'feed',
		 name: URLDecode(nm),
		 link: URLDecode(lnk),
		 picture: URLDecode(pic),
		 caption: URLDecode(capt),
		 description: URLDecode(desc),
		 message: URLDecode(msg)
	   },
	   function(response) {
		 //if (response && response.post_id) {
//		   alert('Post was published.');
//		 } else {
//		   alert('Post was not published.');
//		 }
	   }
	 );
	
	

};
function scaleSize(maxW, maxH, currW, currH){

	var ratio = currH / currW;
	
	if ( (currW >= maxW) && (ratio <= 1)) {
		currW = maxW;
		currH = currW * ratio;
	} 
	
	if (currH >= maxH) {
		currH = maxH;
		currW = currH / ratio;
	}
		
	
	return [Math.floor(currW), Math.floor(currH)];

};
function loadFancyZoom() {

	$.getScript('http://thebarj.com/js/jquery.fancyzoom.min.js', function() {
		$.getScript('http://thebarj.com/js/jquery.ifixpng.js', function() {
			$.getScript('http://thebarj.com/js/jquery.shadow.js', function() {
				$.fn.fancyzoom.defaultsOptions.imgDir='http://thebarj.com/fancyzoom/ressources/';
				$('img.fancyzoom').fancyzoom({Speed:400,imagezindex:5001,showoverlay:true, overlay:0.8});
				
			});
		});  
	});
	
};
function updateTips( t, tips ) {
	tips
		.text( t )
		.addClass( "ui-state-highlight" );
	setTimeout(function() {
		tips.removeClass( "ui-state-highlight", 1500 );
	}, 500 );
};
function checkLength( o, n, min, max, tips ) {
	if ( o.val().length > max || o.val().length < min ) {
		o.addClass( "ui-state-error" );
		updateTips( "Length of " + n + " must be between " +
			min + " and " + max + ".", tips );
		return false;
	} else {
		return true;
	}
};
function checkRegexp( o, regexp, n, tips ) {
	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass( "ui-state-error" );
		updateTips( n, tips );
		return false;
	} else {
		return true;
	}
};
function chekEmail(email, tips) {

	return checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Invalid email address ( eg, you@yourdomain.com)", tips );

};
function stripSpecialChars(str) {
	str=str.replace(/&quot;{1}/gi,"\"").replace(/&apos;{1}/gi,"'");
	return str;
};
function addSpecialChars(string) {
    return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
        .replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
};
function getImage(src) {
	imageObj = new Image();
	imageObj.src=src;
	return imageObj;
};
function getScaledImage(src, maxW, maxH) {
	
	// stupid thing takes tome sometimes
	var counter=0;
	var maxTries=10;
	var loop=true;
	var imageInfo={};
	
	while (loop) {
		
		imageObj = getImage(src);
	
		var sz=scaleImageSize(maxW, maxH, imageObj.width, imageObj.height);
		imageInfo.image=imageObj;
		imageInfo.scaledWidth=sz[0];
		imageInfo.scaledHeight=sz[1];
		counter +=1;
		if ( imageInfo.scaledWidth>0 ) { break; }
		if ( counter > maxTries ) { break; }
	}
	return imageInfo;
};
function loadGalleries(xml, maxW, maxH) {	
	
	var galleries=[];
	
	$(xml).find("gallery").each(function() {
		var gallery={};
		gallery.folder=$(this).attr('folder');
		gallery.name=$(this).attr('name');
		gallery.rootPath=$(this).attr('rootPath');
		gallery.path=$(this).attr('path');
		gallery.description=$(this).attr('description');
		gallery.image=$(this).attr('image');
		
		var galleryItems=[];
		$(this).find("item").each(function() {
			var p = getPic($(this).attr('name'));
			if (p) {
				var item={};
				item.file=$(this).attr('name');
				item.height=$(this).attr('height');
				item.width=$(this).attr('width');
				
				// Scale the image
				var ratio = item.height / item.width;
				var currW=item.width;
				var currH=item.height;
				
				if ( (currW >= maxW) && (ratio <= 1)) {
					currW = maxW;
					currH = currW * ratio;
				} 
				if (currH >= maxH) {
					currH = maxH;
					currW = currH / ratio;
				}
				
				item.scaledHeight=Math.floor(currH);
				item.scaledWidth=Math.floor(currW);
				item.size=$(this).attr('size');
				item.permissions=$(this).attr('permissions');
				item.time=$(this).attr('time');
				item.description=p.description;
				item.id=p.id;
				item.name=p.name;
				item.status=p.status;
				item.url=gallery.rootPath+$(this).parent().attr('path').replace("../","")+'/'+$(this).attr('name');
				item.thumb= 'galleries/thumbs/'+$(this).attr('name');
				galleryItems.push(item);
			}
		});
		gallery.items=galleryItems;
		galleries.push(gallery);
	});

	return galleries;
};
function GalleryLinks(galleries) {
	var galleryLinksDiv='<div id="galleryLinks">';
	$.each(galleries, function() {
    	if ( $(this).attr('folder').toLowerCase() != 'thumbs') { 
			galleryLinksDiv+='<li style="display:none; z-index:10;" path="'+$(this).attr('path')+'">'+$(this).attr('name')+'</li>'; 
		}  
   	});
	galleryLinksDiv+='</div>';
	return galleryLinksDiv;
};
function showContact() {
	
	scroll(0,0);
	 
	$('#contactDiv').remove();
	$('.contentDiv').append('<div style="padding-bottom:15px;"><div id="contactDiv" style="display: none;"></div></div>');
	$('#contactDiv').load('includes/contact_include.php', function() {
										
										$('#contactPanel .input').not('input[type=button]').css('width','400px');
										$('td.label').css('font-weight','bold');
								
										$('#closeButton').unbind().click(function() {
														$('#contactDiv').remove();
														$('#shareOverlay').remove();
														$('#contactButton').show();
														 
													}).button({ label: "Close", icons: {primary:'ui-icon-closethick'} });
										overlay( $('body') );
										var l=Math.floor(( document.width-$('#contactDiv').width() )/2)+'px';
										$('#contactDiv').css('left',l);
										$('#contactDiv').show();
									
									});
	
};
function resetForm(f) {
	$(f).find('.input').each(function(){ $(this).val('').removeClass('ui-state-error') });
	$(f).find('#response').html('');
}
function contactUs(f, subject, to) {
	
	var valid = '';
	var isr = ' is required.';
	var name = $(f).find('#name').val();
	var mail = trim($(f).find("#mail").val());
	
	$(f).find('.input').removeClass('ui-state-error'); 
	
	var text = trim($(f).find("#text").val());
	var ts = trim($(f).find("#ts").val());
	
	if (name.length<1) {
		$(f).find('#name').addClass('ui-state-error'); 
	}
	if (!mail.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
		valid += '<br />A valid Email'+isr;
		$(f).find('#mail').addClass('ui-state-error'); 
	}
	if (text.length<1) {
		valid += '<br />Text'+isr;
		$(f).find('#text').addClass('ui-state-error'); 
	}
	if (valid!='') {
		$(f).find("#response").fadeIn("slow");
		$(f).find("#response").html('One or more errors have ocurred');

	} else {
		 
		$(f).find('.input').attr("disabled","disabled");
		$(f).find('button').attr('disabled','true').fadeTo('slow', 0.2).css('cursor','default');
		$(f).find("#response").css("display", "block").html("Sending message .... ").fadeIn("slow");
		$(f).find("#loading").show();
		
		var from=person(name,mail);
		
		//sendEmail(from, to, text, ts, subject);
		sendEmail(f,from, to, text, ts, subject);
	}
	
}
function sendEmail(f,from, to, msg, ts, subject) {
	
	var datastr ='fromname=' + from.name  + '&frommail=' + from.email  + '&msg=' +  escape(msg)  + '&ts=' + ts;
	datastr += '&toname=' + to.name  + '&tomail=' + to.email  + '&subject=' + subject;
	
	setTimeout( function() {
				$.ajax({
				type: "POST",
				url: "includes/_mail.php",
				data: datastr,
				cache: false,
				success: function(data){
						
						// just in case IE screws up
						var result='';
						var message='An error has ocurred. Please try again later.';
						var status='error';
						
						try { 
							result = JSON.parse(data);
							message=result.msg;
							status=result.status;
						}
						catch(e) {}
						
						$(f).find("#response").html(message);
						$(f).find('.input').removeAttr('disabled');
						$(f).find('button').removeAttr('disabled').fadeTo('slow', 1).css('cursor','pointer');
						$(f).find("#loading").hide();
						if (status=='ok') {
							setTimeout( function() {
									resetForm(f);
									$(f).find("#response").html('');
									try { 
										$(f).find('#closeButton').trigger('click');
									}
									catch(e) {}
									
									
								}, 2000 );
						}
					}
		});
	}, 2000 );
	 
	
};
function person(nm,eml) {
	
	var p={};
	p.name=nm;
	p.email=eml;
	
	return p;
};
function overlay( selector ) {
	
	$(selector).append('<div id="shareOverlay" class="ui-widget-overlay" style="width: '+document.width+'px; height: '+document.height+'px; z-index: 1001;"></div>');

};
function builPic(id, name, url, description, status) {
	var pic={};
	
	pic.id=id;
	pic.name=name;
	pic.url=url;
	pic.description=description;
	pic.status=status;
	
	picsArr.push(pic);
	
};
function setMenuLinks() {
 
 	$('#MenuLinks li.menuLink').hover(
		  function () {
			$(this).addClass('over');
		  }, 
		  function () {
			$(this).removeClass('over');
		  }
		).click(function() {
				//currentLink=$(this).attr('id');
				//location.href=$(this).attr('url');
			
	}); 
	$('#MenuLinks').show();
};
