var base = location.href.toLowerCase().split( ".nsf" )[ 0 ] + ".nsf";
var host = 'www.creeksidevillasofmemorial.com';
var protocol = ( location.href.toLowerCase().indexOf( "https" ) > -1 ) ? "https" : "http";
var isAppRemote = true;
var bustcachevar = 1;
var loadedobjects = "";
var rootdomain = "http://"+window.location.hostname;
var bustcacheparameter = "";
var base = location.href.toLowerCase().split( ".nsf" )[ 0 ] + ".nsf";
var isLoggedIn = ( "anonymous" != "anonymous" ) ? true : false;
var cUser = "Anonymous";
var DEXT={};
String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};
Array.prototype.remove = function(obj) {
  var a = [];
  for (var i=0; i<this.length; i++) {
    if (this[i] != obj) {
      a.push(this[i]);
    }
  }
  return a;
}
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}
function array_replace( arrayName , replaceTo , replaceWith ){
	for( var i = 0 ; i < arrayName.length ; i++ ) {  
		if( arrayName[ i ] == replaceTo ) arrayName.splice( i , 1 , replaceWith );          
	}        
}
function replace_remoteLinks() {
	if ( !isAppRemote ) return;
	var links, link, attr;
	links = document.getElementsByTagName( "a" );
	for ( var l = 0 ; l < links.length ; l++ ) {
		link = links[ l ];
		attr = link.getAttribute( "type" );
		if ( attr ) {
			if ( attr.toLowerCase() == "remote" ) {
				link.href = "#";
				link.onclick = function() {alert( 'This link is only available from within the CGGVeritas intranet.' );return false};
				link.className = "remoteLink";
				//link.setAttribute( "href" , "#" );
				//link.setAttribute( "onClick" , "alert( 'This link is only available from within the CGGVeritas intranet.' );return false" );
				//link.setAttribute( "class" , "remoteLink" );
			}
		}
	}
}
function callAgent( agent, id , func ) {
	var dt = new Date().getTime();
	Ext.Ajax.request({
		method: 'GET',
		disableCaching: true,
		url: base + '/' + agent + '?openagent&unid=' + id,
		success: function( req ) { if ( req.responseText != "" ) alert( req.responseText ); if( func ) eval( func ) },
		failure: function( req ) { alert( 'Error!\nStatusText = ' + req.statusText + '\nContents = ' + req.responseText ); } 
	});
}
function openTabInReadMode() {
	if ( isNewDoc ) {
		parent.tabPanel.remove( parent.tabPanel.getActiveTab() , true );
	} else {
		var tab = parent.tabPanel.getActiveTab();
		var dt = new Date().getTime();
		var strOpenURL = base + "/0/" + tab.getItemId() + "?OpenDocument&dt=" + dt;
		tab.setSrc( strOpenURL );
	}
}
function handlePanelResize( panel, w, h ) {
	if( grid ) { 
		grid.setWidth( ( w - 20 ) );
		grid.syncSize();
	}
}
function ajaxpage( url , containerid , fn ) {
	var page_request = false
	if ( window.XMLHttpRequest ) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} catch ( e ) {
			try {
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			} catch ( e ) {}
		}
	} else
		return false
	page_request.onreadystatechange = function() {
		loadpage( page_request , containerid , fn );
	}
	if ( bustcachevar )
		bustcacheparameter = ( url.indexOf( "?" ) != -1 ) ? "&" + new Date().getTime() : "?" + new Date().getTime();
	page_request.open( 'GET' , url + bustcacheparameter , true );
	page_request.send( null );
}
function loadpage( page_request, containerid , fn ) {
	if ( page_request.readyState == 4 && ( page_request.status == 200 || window.location.href.indexOf( "http" )==-1) ) {
		try {
			if ( document.getElementById( containerid ) ) document.getElementById( containerid ).innerHTML= page_request.responseText;
			if ( fn.trim() != "" ) { 
				//alert( fn );
				setTimeout( fn , 500 ); 
			}
		} catch (e) {
			alert( e. message + " (" + e.name + ")" );
			alert( "An error occurred while attempting to retrieve page information.  Please try again." );
		}
		
	}
}
function get_checked_values( obj ) {
	var checked_values = [];
	for (var i=0; i < obj.length; i++)   {
		if (obj[i].checked) checked_values[ checked_values.length ] = obj[ i ].value;
	}
	return checked_values;
}
function submitFindPeople() {
	var frm = document.forms[ 'searchform' ];
	addFilter( frm );
	return false;
}
function findPeople( frm ){
	var fp_inp = frm.fp_input.value;
	if ( fp_inp.trim() == "" ) return;
	var checked_opts = get_checked_values( frm.fp_cb );
	var search_opts = [];
	var checked_opt;
	for( x = 0 ; x < checked_opts.length ; x++ ) {
		checked_opt = checked_opts[ x ].toLowerCase();
		if ( checked_opt == "name" ) {
			search_opts[ search_opts.length ] = "[sn]=" + fp_inp.trim();
			search_opts[ search_opts.length ] = "[givenname]=" + fp_inp.trim();
		} else {
			search_opts[ search_opts.length ] = "[" + checked_opt + "]=" + fp_inp.trim();
		}
	}
	var searchurl = base + "/(featuredpeople)?SearchView&&start=1&count=10&inp=" + fp_inp + "&query=(" + search_opts.join( " | " ) + ")";
	ajaxpage( searchurl , 'featuredpeoplelist' , '' );
}
function tab_to_tab(e,el) {
    //A function to capture a tab keypress in a textarea and insert 4 spaces and NOT change focus.
    //9 is the tab key, except maybe it's 25 in Safari? oh well for them ...
    if(e.keyCode==9){
        var oldscroll = el.scrollTop; //So the scroll won't move after a tabbing
        e.returnValue=false;  //This doesn't seem to help anything, maybe it helps for IE
        //Check if we're in a firefox deal
      	if (el.setSelectionRange) {
      	    var pos_to_leave_caret=el.selectionStart+4;
      	    //Put in the tab
     	    el.value = el.value.substring(0,el.selectionStart) + '    ' + el.value.substring(el.selectionEnd,el.value.length);
            //There's no easy way to have the focus stay in the textarea, below seems to work though
            setTimeout("var t=$('" + el.id + "'); t.focus(); t.setSelectionRange(" + pos_to_leave_caret + ", " + pos_to_leave_caret + ");", 0);
      	}
      	//Handle IE
      	else {
      		// IE code, pretty simple really
      		document.selection.createRange().text='    ';
      	}
        el.scrollTop = oldscroll; //put back the scroll
    }
}
function launchQuickLink( obj ) {
	var strURL = obj[ obj.selectedIndex ].value;
	var strTitle = obj[ obj.selectedIndex ].text;
	if ( strURL != "" ) {
		shadowOpen( strURL , strTitle );
	}
}
function shadowOpen( sURL , sTitle , sWidth, sHeight ) {
	var theURL = ( sURL.substr( 0 , 1 ) == "~" ) ? protocol + "://" + host + "/" + sURL.substr( 1 ) : sURL;
	Shadowbox.open({
		content:    theURL,
		player:     "iframe",
		title: sTitle,
		width: (sWidth == "" ) ? 650 : sWidth,
		height: (sHeight == "" ) ? 800 : sHeight
	});
}
function imageOpen( sURL , sTitle ) {
	var theURL = ( sURL.substr( 0 , 1 ) == "~" ) ? protocol + "://" + host + "/" + sURL.substr( 1 ) : sURL;
	Shadowbox.open({
		content:    theURL,
		player: "img",
		title: unescape( sTitle ),
		counterType:'skip',
		continuous:true,
		displayCounter:true,
		animSequence:'sync'
	});
}
function prepareGallery() {
	jQuery("a.potwimg").fancybox({ 'hideOnContentClick': false }); 
}
function openProfile( sURL , sTitle ) {
	Shadowbox.open({
		content:    sURL,
		player:     "iframe",
		title: sTitle,
		width: 900,
		height: 420
	});
}
tday = new Array( "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" );
tmonth = new Array( "January","February","March","April","May","June","July","August","September","October","November","December" );
function GetClock(){
	d = new Date();
	nday = d.getDay();
	nmonth = d.getMonth();
	ndate  = d.getDate();
	nyeara = d.getYear();
	nhour  = d.getHours();
	nmin   = d.getMinutes();
	if( nyeara < 1000 ) { nyeara = ( "" + ( nyeara + 11900 ) ).substring( 1 , 5 ); }
	else { nyeara = ( "" + ( nyeara + 10000 ) ).substring( 1 , 5 ); }
	//if(nhour ==  0) {ap = " AM";nhour = 12;} 
	//else if(nhour <= 11) {ap = " AM";} 
	//else if(nhour == 12) {ap = " PM";} 
	//else if(nhour >= 13) {ap = " PM";nhour -= 12;}
	if(nhour <= 9) {nhour = "0" + nhour;}
	if(nmin <= 9) {nmin = "0" + nmin;}
	$( 'clockbox' ).innerHTML = "" + tday[ nday ] + ", " + tmonth[ nmonth ] + " " + ndate + ", " + nyeara + " " + nhour + ":" + nmin + "";
	setTimeout( "GetClock()", 1000 );
}
function getNews( strDirection , strCount , id , view ) {
	//var theURL = ( view.substr( 0 , 1 ) == "~" ) ? protocol + "://" + host + "/" + view.substr( 1 ) : base + "/" + view;
	var curr_Start = jQuery( "#" + id  ).attr( "start" );
	var view_id;
	
	if ( view.indexOf( "/" ) > -1 ) {
		var idx = view.lastIndexOf( "/" );
		view_id = view.substring( idx + 1 );
	} else {
		view_id = view;
	}
	var max = jQuery( "#ViewTotal_" + view_id ).attr( "value" );
	var start;
	
	switch ( strDirection.toLowerCase() ) {
		case "begin":
			start = 1;
			break;
			
		case "previous":
			var prevNum = ( parseInt( curr_Start ) - parseInt( strCount ) );
			start = ( prevNum < 0 ) ? 1 : prevNum;
			break;
		case "next":
			var nextNum = ( parseInt( curr_Start ) + parseInt( strCount ) );
			start = ( nextNum >= parseInt( max ) ) ? parseInt( max ) : nextNum;
			break;
		case "end":
			var possibleEnd = parseInt( max ) - parseInt( strCount );
			start = ( possibleEnd < 0 ) ? max : possibleEnd;
			break;
	}
	ajaxpage( view + "?openview&Start=" + start + "&Count=" + strCount  , id , 'jQuery( "#rone" ).equalHeights();' ); 
	jQuery( "#" + id ).attr( {start : start} );
}
function searchContacts( strDirection , strCount ) {
	var curr_Start = jQuery( "#featuredpeople"  ).attr( "start" );
	var view_id;
	
	var max = jQuery( "#TotalHits" ).attr( "value" );
	var start;
	
	if ( strDirection.toLowerCase() == "previous" ) {
		if ( curr_Start == 1 ) return;
		var prevNum = ( parseInt( curr_Start ) - parseInt( strCount ) );
		start = ( prevNum < 0 ) ? 1 : prevNum;
	} else {
		var nextNum = ( parseInt( curr_Start ) + parseInt( strCount ) );
		start = ( nextNum >= parseInt( max ) ) ? parseInt( max ) : nextNum;
	}
	var strQuery = jQuery( "#Query" ).attr( "value" );
	ajaxpage( "featuredpeople?searchview&Start=" + start + "&Count=" + strCount + "&query=" + strQuery + "&searchorder=4"  , "featuredpeople" , 'jQuery( "#rone" ).equalHeights();' ); 
	jQuery( "#featuredpeople" ).attr( {start : start} );
}
function getMyContacts( strDirection , strCount , id , view , me ) {
	var theURL = ( view.substr( 0 , 1 ) == "~" ) ? protocol + "://" + host + "/" + view.substr( 1 ) : base + "/" + view;
	var curr_Start = jQuery( "#" + id  ).attr( "start" );
	var view_id;
	
	if ( view.indexOf( "/" ) > -1 ) {
		var idx = view.lastIndexOf( "/" );
		view_id = view.substring( idx + 1 );
	} else {
		view_id = view;
	}
	var max = jQuery( "#ViewTotal_" + view_id ).attr( "value" );
	if ( max == "0" ) return;
	var start;
	
	if ( strDirection.toLowerCase() == "previous" ) {
		var prevNum = ( parseInt( curr_Start ) - parseInt( strCount ) );
		start = ( prevNum <= 0 ) ? 1 : prevNum;
	} else {
		var nextNum = ( parseInt( curr_Start ) + parseInt( strCount ) );
		start = ( nextNum >= parseInt( max ) ) ? parseInt( max ) : nextNum;
	}
	
	ajaxpage( theURL + "?openview&Start=" + start + "&Count=" + strCount + "&RestrictToCategory=" + me , id , 'jQuery( "#rone" ).equalHeights();' ); 
	jQuery( "#" + id ).attr( {start : start} );
}
function openMyProfile(){
	var me = 'Anonymous';
	if ( me.toLowerCase() == "anonymous" ) {
		alert( "You must be signed in to open your profile." );
	} else {
		location = base + "/ppr?open"
	}
}
function initMenus() { 
	jQuery( 'div.accordionButton' ).click( function() {
		if( jQuery( this ).next().is( ':visible' )) {
			jQuery( 'div.accordionContent' ).slideUp( 'normal' );
			jQuery( 'div.accordionButtonSelected' ).removeClass().addClass( 'accordionButtonSelected' );
			jQuery( this ).removeClass().addClass( 'accordionButton' );
			initSubMenus( jQuery( this ).next() );
		} else {
			jQuery( 'div.accordionContent' ).slideUp( 'normal' );
			jQuery( this ).next().slideDown( 'normal' );
			jQuery( 'div.accordionButtonSelected' ).removeClass().addClass( 'accordionButton' );
			jQuery( this ).removeClass().addClass( 'accordionButtonSelected' );
			initSubMenus( jQuery( this ).next() );
		}
	});
	jQuery( 'div.accordionSubButton' ).click( function() { 	
		if ( jQuery( this ).next().is( ":visible" ) ) {
			var className = "accordionSubButton";
			createCookie( this.id , 'none' , 365 );
		} else {
			var className = "accordionSubButtonSelected";
			createCookie( this.id , 'block' , 365 );
		} 		
		jQuery(this).next().toggle('normal');
		jQuery(this).removeClass().addClass( className );
		return false;
	}).next().hide();

	jQuery( 'div.accordionContent' ).hide();
}
function initSubMenus( el ) {
	var subitems = jQuery( el ).find( '.accordionSubButton' );
	if ( subitems.length == 0 ) {
		subitems = jQuery( el ).find( '.accordionSubButtonSelected' );
		if ( subitems.length == 0 ) return false;
	}
	for ( x = 0 ; x < subitems.length ; x++ ) {
		var ele = subitems[ x ];
		var nEle = $( "sub_" + ele.id );
		var cookie = readCookie( ele.id );
		if ( cookie == "" || cookie == null ) {
			cookie = "none";
		}
		if ( cookie == "block" ) {
			if ( nEle ) nEle.style.display = "block";
			ele.className = "accordionSubButtonSelected";
		} else {
			if ( nEle ) nEle.style.display = "none";
			ele.className = "accordionSubButton";
		}
		
	}
}
function clearInitialValue( obj , strToCompare ) {
	if ( obj.value == strToCompare ) obj.value = "";
}
function restoreInitialValue( obj, strToRestore ) {
	if ( obj.value.trim() == "" ) obj.value = strToRestore
}
function checkForArchors(){
	var url = window.location.href;
	var idx = url.indexOf( "#" );
	if ( idx > -1 ) {
		var anchor = url.substr( ( idx + 1 ) );
		eval( 'window.location.hash = "' + anchor + '"');
	}
}
function showandslide( id ) {
	var obj = jQuery( "#" + id );
	jQuery( "#" + id ).toggle( 'normal' );	
	var lnkObj = jQuery( "#" + id + "_lnk" );
	var strTxt = lnkObj.text();
	var strTxt_before = ( strTxt.indexOf( "Edit" ) > -1 ) ? "Edit" : "Close";
	var strTxt_after = ( strTxt.indexOf( "Edit" ) > -1 ) ? "Close" : "Edit";
	var strTxt_altered = strTxt.replace( strTxt_before , strTxt_after );
	lnkObj.text( strTxt_altered );
}
function toggleFileUpload() {
	jQuery( "#dspFileUpload_edit" ).toggle( 'normal' );
}
function validateCommentSubmit() {
	var doc = document.forms[ '_Contact' ];
	var errMsg = [];
	if ( doc.name.value.trim() == "" || doc.name.value.trim() == "Your Name" ) errMsg[ errMsg.length ] = "Name";
	if ( doc.email.value.trim() == "" || doc.email.value.trim() == "Your Email" ) errMsg[ errMsg.length ] = "Email";
	if ( doc.phone.value.trim() == "" || doc.phone.value.trim() == "Your Phone" ) errMsg[ errMsg.length ] = "Phone";
	if ( doc.message.value.trim() == "" ) errMsg[ errMsg.length ] = "Message";
	
	if ( errMsg.length > 0 ) { // errors exist
		alert( "Please complete:  " + errMsg.join( ", " ) );
		return false	
	} else {
		doc.submit();
	}
}
function strLeft( sourceStr , keyStr ) {
	return ( sourceStr.indexOf( keyStr ) == -1 | keyStr == '' ) ? '' : sourceStr.split( keyStr )[ 0 ];
}
function strRight( sourceStr , keyStr ) {
	idx = sourceStr.indexOf( keyStr );
	return (idx == -1 | keyStr == '' ) ? '' : sourceStr.substr( idx + keyStr.length );
}
DEXT.Rate = function(id, rate){
	jQuery("#rating").html("<span class=\"spin\">Casting your rating...</spin>");
	jQuery("ul.star-rating li a").css({"cursor":"progress"});
	var user = "Anonymous";
	setTimeout(function(){
		jQuery.getJSON("Rate?OpenAgent", { id: id, ajax: true, user : user, rate: rate, _: new Date().getTime()}, function(data){
		  jQuery("#rating").css({"background": "none"});
		  jQuery("#rating").html("<span class=\""+((data.success)?"tick":"cross")+"\">"+data.message+"</span>");
		  jQuery("li.current-rating").css("width", ((parseFloat(data.rating)/5)*125)+"px");
		  if (data.success){
		  	jQuery("#rating-summary").text("This is currently rated "+data.rating+" out of 5 Stars, based on "+data.votes+" ratings.")
		  }
		  jQuery("ul.star-rating li a").css({"cursor":"pointer"});
		});
	}, 3000); //3s pause to give spinner gif chance to convey its message
}
function createCookie( name , value , days ) {
	if ( days ) {
		var date = new Date();
		date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
		var expires = "; expires=" + date.toGMTString();
	}  else var expires = "";
	document.cookie = name + "=" + escape( value ) + expires + "; path=/";
}
function setCookie( name , value , expires , path , domain , secure ) {
	document.cookie= name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}
function readCookie( name ) {
	var ca = document.cookie.split( ';' );
	var nameEQ = name + "=";
	for( var i = 0 ; i < ca.length ; i++ ) {
		var c = ca[ i ];
		while ( c.charAt( 0 ) == ' ' ) c = c.substring( 1 , c.length ); //delete spaces
		if ( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
	}
	return null;
}
function eraseCookie( name ) {
	createCookie( name , "" , -1 );
}
