// JavaScript Document
/* Utility functions */

var prfSp=[];
var currPrf=0;
var getListed;

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)
	// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can 
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie 
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    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 path="'+$(this).attr('path')+'">'+$(this).attr('name')+'</li>'; 
		}  
   	});
	galleryLinksDiv+='</div>';
	return galleryLinksDiv;
}
