// 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=[];
var active_element='0';
var myService;
var feedUrl;
 
var email_pattern=/^((([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;

// Error Messages
var msg_required='* Required';
var msg_invalied_email='Invalid email address ( You@YourrDomain.Com )';
var webmaster=person( 'John Dodd', 'john@thebarj.com' );
var browser = new BrowserInfo();

var closeImage=getImage('http://thebarj.com/fancyzoom/ressources/closebox.png');

// Google Calendar Functions
function setupMyService( service ) {
  myService = new google.gdata.calendar.CalendarService( service );
}
function googleDate(gDate){
	
	
	var p = gDate.indexOf('T');
	var dts=gDate.substr(0,p);
	var tms=gDate.substr(p);
	var th=tms.indexOf(':');
	var tm=tms.indexOf(':',th+1);
	var h= tms.substr(1, th );
	var m= tms.substr(th+1, tm );
	var p = tms.indexOf('-');
	tms=tms.substr(0,p);
	var ds=dts.replace(/\-/ig, '/')+tms;
	
	var d=new Date(ds);
	d.setHours(parseInt(h),parseInt(m));
	return d;
}
function getMyFeed(  service, feedUrl, days ) {
 	
	setupMyService( service );
 	
	var query = new google.gdata.calendar.CalendarEventQuery(feedUrl);
	
	startDate = new Date(); // Use today for begin date
	endDate = new Date(); // Next we will add # of days from Today
	endDate.setDate( endDate.getDate() + days ); 
	
	var startDateTime = new google.gdata.DateTime(startDate, true);
	var endDateTime = new google.gdata.DateTime(endDate, true);
	
	query.setMinimumStartTime(startDateTime);
	query.setMaximumStartTime(endDateTime);
	
	query.setMaxResults(500);
	query.setOrderBy('starttime');
	query.setSortOrder('a');
	
  	myService.getEventsFeed(query, feed_handler, error_handler );
}
function BrowserInfo() {
  this.name = navigator.appName;
  this.isIE=false;
  if ( this.name == "Microsoft Internet Explorer" ) this.isIE=true;
  this.codename = navigator.appCodeName;
  this.version = navigator.appVersion.substring(0,4);
  this.platform = navigator.platform;
  this.javaEnabled = navigator.javaEnabled();
  this.screenWidth = screen.width;
  this.screenHeight = screen.height;
}
function test() {
	
	var msg='this is a test';
	reportError(msg);
}
// Functions
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 valid_email(email) {
	if ( !( email_pattern.test( email.val() ) ) ) {
		return false;
	} else {
		return true;
	}
}
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) {
	$(':input',f)
	 .not(':button, :submit, :reset, :hidden')
	 .val('')
	 .removeAttr('checked')
	 .removeAttr('selected');
	$(f).find('.input').each(function(){ $(this).val('').removeClass('ui-state-error') });
	$(f).find('#response').html('').removeClass();
	$(f).find('.input').not('.input-normal').addClass('input-normal'); 
	$(f).find('.ui-error-text').remove();
	return false;
}
function errorInfo(obj, msg) {
	var error=$('<div class="ui-error-text"></div>');
	$(error).html(msg).css({ 'color':'#900','font-family':'"Times New Roman", Times, serif','font-size':'0.8em'});
	$(error).insertAfter( obj );
}
function reportError(msg){

	$.get('includes/token.php', function(data) {	
			result = JSON.parse(data);
			var details='<h2>An error has ocurred</h2>';
			details+='Time: '+new Date().toString();
			details+='<br>Url:'+location.href+'<br><hr>';
			sendEmail($('<form></form>'), webmaster, webmaster, details+msg, result.token, 'ERROR REPORT');
		});
	
}
function contactUs(f, subject, to) {
	
	var valid = true;
	
	$(f).find('.ui-error-text').remove();
	$(f).find('.input').removeClass('ui-state-error'); 
	$(f).find('.input').not('input-normal').addClass('input-normal'); 
	
	var text = trim($(f).find("#text").val());
	
	$(f).find('.required').each(function(){  
										 
										 if ( $(this).val().length<1) {
											valid = false;
											$(this).addClass('ui-state-error');
											errorInfo( this , msg_required);
										}
									});
	$(f).find('.required.email').not('.ui-state-error').each(function(){  
										 
										 if ( !valid_email( $(this) ) ) {
											valid = false;
											$(this).addClass('ui-state-error');
											errorInfo( $(this) , msg_invalied_email);
										}
									});
	
	if ( !valid ) {
		$(f).find("#response").fadeIn("slow");
		$(f).find("#response").html('One or more errors have ocurred');
		$(f).find('.ui-state-error').removeClass('input-normal');
		$('.ui-error-text').css('color',$('#response').css('color'));

	} 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 name = trim($(f).find('#name').val());
		var mail = trim( $(f).find("#mail").val());
		var from=person(name,mail);
		
		$("#ts").remove();
		$.get("includes/token.php",function(data){
				result = JSON.parse(data);
				sendEmail(f, from, to, text, result.token, 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;
	
	if ( $(f).find('#email_path').length > 0 ) { 
		datastr += '&email_path=' + $(f).find('#email_path').val(); 
	} 
	
	setTimeout( function() {
				$.post({
				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();
};
function showOverlay() {
	
	
	$('#shareOverlay').remove();
	var h = $('body').height()+20;
	
	$('body').append('<div id="shareOverlay" class="ui-widget-overlay" style="width: '+screen.availWidth+'px; height: '+h+'px; z-index: 1001; opacity:0.7;Alpha(Opacity=70);"></div>');

	
	 
}
function loadForm(path,title, cb, type){
	
	var t=5;
	var w=940;
	if (!type) var type=path.substring(trim(path).length-3).toLowerCase();
	//var h=500;
	var h = Math.floor($(window).height()*.95);

	$(window).scrollTop(0); 
	$('#reportWrapper').remove();
	showOverlay();
	
	var l=Math.floor(($('body').width()-w)/2);
	
	$('body').append('<div id="reportWrapper"><style type="text/css">#formWrapper {background-color: #FFF; display: block; padding: 0px; height: 10px; width: 10px;overflow: hidden;position: absolute;z-index: 2001;top:'+t+'px;left:'+l+'px;</style><div id="formWrapper" class="ui-corner-all"></div></div>');
	
	$('#formWrapper').append(' <div id="boxHeader" class="ui-widget-header ui-corner-top"><div><img id="closeButton" style="cursor:pointer;" title="Close" class="closeButton" align="right" src="http://thebarj.com/fancyzoom/ressources/closebox.png" width="30" \></div><h3 style="font-size:1.6em;" align="center">'+title+'</h3></div><div id="report" style="height:'+h+'px; padding-left:5px; padding-right:px; overflow:auto;"></div>');
	
	$('#formWrapper #closeButton').click(function(){
												  	$('#loading_bg').remove();
													$('#formWrapper').animate({
														opacity: '0',					 
														height: 0,
														width: 0
													  }, speed, easing, function() { 
																			
																$('#reportWrapper').remove();
																$('#shareOverlay').remove();
																$(this).remove();
																if (cb) {
																	var f = new Function( cb );
																	f();
																}
																
															});
													
													
												  });
	
	if (type=='pdf') {
		path=path.replace("includes/forms/_pdf_viewer.php?form=","");
		$('#formWrapper #report').load('includes/forms/_pdf_viewer2.php', function() { 	
															var frmH =  Math.floor(h*.85);
															$('#reportWrapper #pdfDiv').attr('height',frmH+'px'); 
															animateReportWrapper(type,h,w,path);
														});
		
	} else if (type=='path') {
		
		$('#formWrapper #report').load('includes/forms/_empty_form.php',path, function() { 	
															var frmH =  Math.floor(h*.85);
															$('#reportWrapper #pdfDiv').attr('height',frmH+'px'); 
															animateReportWrapper(type,h,w,path);
														});
		
		
	} else {
		$('#formWrapper #report').load(path, function() { 	var frmH =  Math.floor(h*.85);
															
															$('#reportWrapper').find('iframe').attr('height',frmH+'px'); 
															animateReportWrapper(type,h,w,path);
														});
	}
	
	
	
	
	
}
function animateReportWrapper(type,h,w,path) {
	
	if (!default_form_message) var default_form_message='';
	
	$('#formWrapper').animate({
						opacity: '1',					 
						height: h,
						width: w
					  }, speed, easing, function() { 
									$('#loading_bg').remove();
									var bg=$('<div id="loading_bg" style="width: 350px; height: 200px; z-index: 2001;padding-top:70px;"></div>');
									$(bg).css({'position':'absolute','left':'400px','top':'200px'}).append('<div><p style="color:#058EF9;font-size:1.5em;">Loading form, please wait.</p><img id="loading_bar" src="images/ajax-loader-bar.gif" /></div>');
									$('body').append(bg);
									
									//set height
									var h=$('#formWrapper').height();
									h=$('#formWrapper').height()-Math.floor(h*.09);
									$('#pdf').css('height',h+'px');
									
		 							if (type=='pdf') {
										
										
										var myPDF = new PDFObject({ 
		
											url: path,
											pdfOpenParams: {
												navpanes: 1,
												toolbar: 1,
												statusbar: 1
											}
										
										});
										
										if (myPDF) { 
											myPDF.embed("pdf"); 
											var x= myPDF.get('pdfobjectversion');
											var a=1;
											//$('#form_loading_Div').hide();
											
										} else { 
											$('#pdf').html('<div style="padding:20px;" class="ui-state-error"><h2 style="padding:15px 0px;">An error has ocurred opening this file.<br><br> Please try again later. We apologise for any inconvenience.</h2></div>');
											reportError( $('#pdf').html() );
										}
										
									} else {
									
										$('#loading_bg').remove();
									}
									
									var rh=Math.floor($('#formWrapper').height()-$('#boxHeader').height());
									$('#formWrapper #report').css('height',rh+'px');
									$('#report input').each(function(){ $(this).attr('id', $(this).attr('name') ); });
									$('#formWrapper #report #buttonBar .reset').button({ label: "Reset", icons: {primary:'ui-icon-refresh'} });
									$('#formWrapper #report #buttonBar .submit').button({ label: "Submit", icons: {primary:'ui-icon-check'} });
									$("#formWrapper #response").html( default_form_message ).show();
									$('.required').each( function(){ $('<span class="req_marker">*</span>').insertBefore($(this)); });
									$('#formWrapper #report #buttonBar .reset').click(function(){ resetForm( $('#formWrapper').find('form')) ;});
									$('#formWrapper #report #buttonBar .submit').click(function(){ sendForm( $('#formWrapper').find('form')) ;});
							});
}
function loadVideo(path,title){
	
	//title=path;
	
	var t=5;
	var w=940;
	var type=path.substring(trim(path).length-3).toLowerCase();
	//var h=500;
	var h = Math.floor($(window).height()*.95);

	$(window).scrollTop(0); 
	$('#popupWrapper').remove();
	showOverlay();
	
	var l=Math.floor(($('body').width()-w)/2);
	
	$('body').append('<div id="popupWrapper"><style type="text/css">#videoWrapper {background-color: #FFF; display: block; padding: 0px; height: 10px; width: 10px;overflow: hidden;position: absolute;z-index: 2001;top:'+t+'px;left:'+l+'px;</style><div id="videoWrapper" class="ui-corner-all"></div></div>');
	
	$('#videoWrapper').append(' <div id="boxHeader" class="ui-widget-header ui-corner-top"><div><img id="closeButton" style="cursor:pointer;" title="Close" class="closeButton" align="right" src="http://thebarj.com/fancyzoom/ressources/closebox.png" width="30" \></div><h3 style="font-size:1.6em;" align="center">'+title+'</h3></div><div id="video" style="height:'+h+'px; padding-left:5px; padding-right:px; overflow:auto;"></div>');
	
	$('#videoWrapper #closeButton').click(function(){
												  	$('#loading_bg').remove();
													$('#videoWrapper').animate({
														opacity: '0',					 
														height: 0,
														width: 0
													  }, speed, easing, function() { 
																			
																$('#popupWrapper').remove();
																$('#shareOverlay').remove();
																$(this).remove();
																
															});
													
													
												  });
	

	var url='includes/forms/_video_viewer.php'; //?path='+path;
	$('#videoWrapper #video').load(url, {path: path}, function() { 	
															
	
		$('#videoWrapper').animate({
						opacity: '1',					 
						height: h,
						width: w
					  }, speed, easing, function() { 
									$('#loading_bg').remove();
									var bg=$('<div id="loading_bg" style="width: 350px; height: 200px; z-index: 2001;padding-top:70px;"></div>');
									$(bg).css({'position':'absolute','left':'400px','top':'200px'}).append('<div><p style="color:#058EF9;font-size:1.5em;">Loading video, please wait.</p><img id="loading_bar" src="images/ajax-loader-bar.gif" /></div>');
									$('body').append(bg);
									
									var h=$('#videoWrapper').height();
									h=$('#videoWrapper').height()-Math.floor(h*.09);
									var rh=Math.floor($('#videoWrapper').height()-$('#boxHeader').height());
									$('#videoWrapper #video').css('height',rh+'px');
									
							});
	
	
	});
	
}
function perform_acrobat_detection() { 
  //
  // The returned object
  // 
  var browser_info = {
    name: null,
    acrobat : null,
    acrobat_ver : null
  };

  if(navigator && (navigator.userAgent.toLowerCase()).indexOf("chrome") > -1) browser_info.name = "chrome";
  else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("msie") > -1) browser_info.name = "ie";
  else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("firefox") > -1) browser_info.name = "firefox";
  else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("msie") > -1) browser_info.name = "other";


 try
 {
  if(browser_info.name == "ie")
  {          
   var control = null;

   //
   // load the activeX control
   //                
   try
   {
    // AcroPDF.PDF is used by version 7 and later
    control = new ActiveXObject('AcroPDF.PDF');
   }
   catch (e){}

   if (!control)
   {
    try
    {
     // PDF.PdfCtrl is used by version 6 and earlier
     control = new ActiveXObject('PDF.PdfCtrl');
    }
    catch (e) {}
   }

   if(!control)
   {     
    browser_info.acrobat == null;
    return browser_info;  
   }

   version = control.GetVersions().split(',');
   version = version[0].split('=');
   browser_info.acrobat = "installed";
   browser_info.acrobat_ver = parseFloat(version[1]);                
  }
  else if(browser_info.name == "chrome")
  {
   for(key in navigator.plugins)
   {
    if(navigator.plugins[key].name == "Chrome PDF Viewer" || navigator.plugins[key].name == "Adobe Acrobat")
    {
     browser_info.acrobat = "installed";
     browser_info.acrobat_ver = parseInt(navigator.plugins[key].version) || "Chome PDF Viewer";
    }
   } 
  }
  //
  // NS3+, Opera3+, IE5+ Mac, Safari (support plugin array):  check for Acrobat plugin in plugin array
  //    
  else if(navigator.plugins != null)
  {      
   var acrobat = navigator.plugins['Adobe Acrobat'];
   if(acrobat == null)
   {           
    browser_info.acrobat = null;
    return browser_info;
   }
   browser_info.acrobat = "installed";
   browser_info.acrobat_ver = parseInt(acrobat.version[0]);                   
  }


 }
 catch(e)
 {
  browser_info.acrobat_ver = null;
 }

  return browser_info;
}
var PDFObject = function (obj){
	
	if(!obj || !obj.url){ return false; }

	var pdfobjectversion = "1.2",
		//Set reasonable defaults
		id = obj.id || false,
		width = obj.width || "100%",
		height = obj.height || "100%",
		pdfOpenParams = obj.pdfOpenParams,
		url,
		pluginTypeFound;
	
	//Tests specifically for Adobe Reader (aka Acrobat) in Internet Explorer
	var hasReaderActiveX = function (){

		var axObj = null;
		
		if (window.ActiveXObject) {
			
			axObj = new ActiveXObject("AcroPDF.PDF");
				
			//If "AcroPDF.PDF" didn't work, try "PDF.PdfCtrl"
			if(!axObj){
				axObj = new ActiveXObject("PDF.PdfCtrl");
			}
			
			//If either "AcroPDF.PDF" or "PDF.PdfCtrl" are found, return true
			if (axObj !== null) {
				return true;
			}
	
		}
		
		//If you got to this point, there's no ActiveXObject for PDFs
		return false;
		
	};



	//Tests specifically for Adobe Reader (aka Adobe Acrobat) in non-IE browsers
	var hasReader = function (){
	
		var i,
			n = navigator.plugins,
			count = n.length,
			regx = /Adobe Reader|Adobe PDF|Acrobat/gi;
		
		for(i=0; i<count; i++){
			if(regx.test(n[i].name)){
				return true;
			}
		}
		
		return false;
	
	};


	//Detects unbranded PDF support
	var hasGeneric = function (){
		var plugin = navigator.mimeTypes["application/pdf"];
		return (plugin && plugin.enabledPlugin);
	};
	

	//Determines what kind of PDF support is available: Adobe or generic
	var pluginFound = function (){
	
		var type = null;
		
		if(hasReader() || hasReaderActiveX()){
			
			type = "Adobe";
		
		} else if(hasGeneric()) {
		
			type = "generic";
		
		}
		
		return type;
	
	};


	//If setting PDF to fill page, need to handle some CSS first
	var setCssForFullWindowPdf = function (){
		
		var html = document.getElementsByTagName("html");
		if(!html){ return false; }
		
		var html_style = html[0].style,
			body_style = document.body.style;
		
		html_style.height = "100%";
		html_style.overflow = "hidden";	
		body_style.margin = "0";
		body_style.padding = "0";
		body_style.height = "100%";
		body_style.overflow = "hidden";
		
	};


	//Creating a querystring for using PDF Open parameters when embedding PDF
	var buildQueryString = function(pdfParams){
		
		var string = "",
			prop;
		
		if(!pdfParams){ return string; }
		
		for (prop in pdfParams) {
			
			if (pdfParams.hasOwnProperty(prop)) {
				
				string += prop + "=";
				
				if(prop === "search") {
					
					string += encodeURI(pdfParams[prop]);
				
				} else {
					
					string += pdfParams[prop];
					
				}	
				
				string += "&";
				
			}
			
		}
		
		//Remove last ampersand
		return string.slice(0, string.length - 1);
	
	};


	//Simple function for returning values from PDFObject
	var get = function(prop){

		var value = null;

		switch(prop){
			case "url" : value = url; break;
			case "id" : value = id; break;
			case "width" : value = width; break;
			case "height" : value = height; break;
			case "pdfOpenParams" : value = pdfOpenParams; break;
			case "pluginTypeFound" : value = pluginTypeFound; break;
			case "pdfobjectversion" : value = pdfobjectversion; break;
		}

		return value;

	};


	/* ----------------------------------------------------
	   PDF Embedding functions
	   ---------------------------------------------------- */

	
	var embed = function(targetID){

		if(!pluginTypeFound){ return false; }

		var targetNode = null;

		if(targetID){

			//Allow users to pass an element OR an element's ID
			targetNode = (targetID.nodeType && targetID.nodeType === 1) ? targetID : document.getElementById(targetID);
			
			//Ensure target element is found in document before continuing
			if(!targetNode){ return false; }

		} else {

			targetNode = document.body; 
			setCssForFullWindowPdf();
			width = "100%";
			height = "100%";

		}

		targetNode.innerHTML = '<object	data="' +url +'" type="application/pdf" width="' +width +'" height="' +height +'"></object>';


		return targetNode.getElementsByTagName("object")[0];

	};

	//The hash (#) prevents odd behavior in Windows
	//Append optional Adobe params for opening document
	url = encodeURI(obj.url) + "#" + buildQueryString(pdfOpenParams);
	pluginTypeFound = pluginFound();
	
	this.get = function(prop){ return get(prop); };
	this.embed = function(id){ return embed(id); };
	
	return this;
	
};
(function($) {
    $.eventReport = function(selector, root) {
        var s = [];
        $(selector || '*', root).andSelf().each(function() {
            var e = $.data(this, 'events');
            if(!e) return;
            s.push(this.tagName);
            if(this.id) s.push('#', this.id);
            if(this.className) s.push('.', this.className);
            for(var p in e) { 
				if (p=="click") {
					s.push('\n', p);
            		s.push('\n\n');
				}
			}
        });
        return s.join('');
    }
    $.fn.eventReport = function(selector) {
        return $.eventReport(selector, this);
    }
})(jQuery);
