$(function() {
	$("#agentlink").click(function() {
		$.get("agentinsertclick.php", {agentid: $("#agentid").val(), cliqurl: this.href}, function(result) {
			$("#status").html( result ).fadeIn();
		})
	})
});
$(function() {
        $("#agentlistlink").click(function() {
                $.get("agentinsertclick.php", {agentid: $("#agentid").val(), cliqurl: this.href}, function(result) {
                        $("#status").html( result ).fadeIn();
                })
        })
});
function setType(typename) 
{
	if(typename) {
		href=location.href;
		window.location = this.href+"&type="+typename;
		return;
	}
}

function validateUserAge(age,limit,responseId,form,assume)
{
	// If assume is set, we do no calculations and instead base it off pre-selected years
	if(assume) {
		if(form) {
			if(age != "") {
			form.submit.disabled = false;
			} else {
			form.submit.disabled = true;
			}
		}
	} else {
	if(age < limit) {
		document.getElementById(responseId).innerHTML = "You must be at least "+limit+" years old to continue";
		if(form) {
			form.submit.disabled = true;
		}
	} else {
		if(form) {
			form.submit.disabled = false;
		}
	}
	}
}

/* Check file extension against a comma separated extension string */
function checkExtension(string,extensionString) {
	if(string == "") return 3;
	var extensions = extensionString.split("|");
	var filename = string;
	var dot = filename.lastIndexOf("."); 
	var extension = filename.substr(dot,filename.length); 
	var retValue = 0;
	for(var i=0;i<=extensions.length;i++) {
		if(extension == extensions[i]) {
			retValue = 1;
		}
	}
	return retValue;
}

/* Vaidate a selected image file name */
function validateImage(form) {
	iextensions = ".jpg|.jpeg";
        var txtnode = document.getElementById("imagemessage");
	var result = checkExtension(form.image.value,iextensions)
	if(result == 0) {
		txtnode.innerHTML = "That file is not a jpeg/jpg! Try again!";
                txtnode.style.display = "block";
	} else if(result == 1){
		txtnode.innerHTML = "Valid file!";
       	       txtnode.style.display = "block";
	} else {
		txtnode.style.display = "none";
	}

}

/* Load our sponsor/contribute forms via AJAX */
var userid = null;
var prevform = "";
function showForm(formnum,cityid,blogid,type,userid,prevform)
{
        if(!type) {
                var type = "sponsor";
        }
        var fileName;
        var divName;
        if(type == "sponsor") {
                fileName = "getSponsorFormBeta.php";
                divName = "sponsorform";
        } else if(type == "contribute") {
                fileName = "getContribForm.php";
                divName = "contribform";
        }
                var requestUrl = "";
                switch(formnum)
                {
                        case 1:
                        requestUrl = fileName+"?id=1&cityid="+cityid+"&blogid="+blogid+"&url="+location.href+"&userid="+userid;
                        break;
                        case 2:
                        return showFeaturedForm(cityid,blogid,userid);
                        //requestUrl = fileName+"?id=2&cityid="+cityid+"&blogid="+blogid+"&url="+location.href+"&userid="+userid;
                        break;
                        case 3:
                        requestUrl = fileName+"?id=3&cityid="+cityid+"&blogid="+blogid+"&url="+location.href+"&userid="+userid;
                        break;
                        case 4:
                        requestUrl = fileName+"?id=4&prevform="+prevform+"&cityid="+cityid+"&blogid="+blogid+"&url="+location.href;
                        break;
                        case 5:
                        requestUrl = fileName+"?id=5&prevform="+prevform+"&cityid="+cityid+"&blogid="+blogid+"&url="+location.href;
                        break;
                        case 6:
                        requestUrl = fileName+"?id=6&prevform="+prevform+"&cityid="+cityid+"&blogid="+blogid+"&url="+location.href+"&userid="+userid;
                        break;
                }
                // Loading...
                var loadingtxt = document.getElementById(divName);
                loadingtxt.innerHTML = "Loading...";
                //HTML_AJAX.replace(divName,requestUrl);
                $("#"+divName).load("/"+requestUrl).fadeIn();
                var err = document.getElementById("validateMessage");
                err.innerHTML = "";
                err.style.display = "none";

                var err1 = document.getElementById("errortitle");
                if(err1) {
                err1.style.display = "none";
                }
}

var userid = '';
function showFeaturedForm(cityid,blogid,userid) {
	var beta = '&beta=1';
        var requestUri = '';
        requestUri = "id=2&cityid="+cityid+"&blogid="+blogid+"&url="+location.href+"&userid="+userid+beta;
	$('#sponsorform').load('/getSponsorFormBeta.php?'+requestUri).fadeIn('fast');
}        

/* The redirector for our main drop downs */
function sendToSelection()
{
	var state = document.getElementById("stateselect");
	var city = document.getElementById("cityselect");
	var stateindex = document.getElementById("stateselect").selectedIndex;
	var cityindex = document.getElementById("cityselect").selectedIndex;
	var selectedState = state.options[stateindex].text;
	var selectedCity = city.options[cityindex].text;
	if(selectedCity == "--Select City--") return false;
	selectedState = selectedState.toLowerCase();
	selectedCity = selectedCity.toLowerCase();
	selectedState = selectedState.replace(" ","");
	selectedCity = selectedCity.replace(" ","");
	selectedCity = selectedCity.replace(" ","");
	selectedCity = selectedCity.replace(" ","");
	selectedState = selectedState.replace(".","");
	//selectedCity = selectedCity.replace(".","");
	var nlocation = "http://"+selectedCity+"."+selectedState+"blogpage.com";
	parent.window.location = nlocation;
}

/*
^ Used in the state landing pages to send to a city landing page
*/
function sendCityLanding(script)
{
	if(!script) {
	var script = "contribute.php";
	}
        var city = document.getElementById("cityselect");
        var cityindex = document.getElementById("cityselect").selectedIndex;
        var nlocation = city.options[cityindex].value+"/"+script;
     	
        window.location = nlocation;
}



function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}

function keyValidateEmail(str)
{
	if(str)
	{
		var valid = validateEmail(str);
		var strO = document.getElementById("emailmessage");
		if(valid == 1) {
		strO.style.color="green";
		strO.innerHTML = "Email is valid!";
		} else {
		strO.style.color="#B01111";
		strO.innerHTML = "Email is invalid! Keep trying!"
		}
		strO.style.display = "block";
	return false;
	}
}

function retrieveCategoryStatus(id,cityid,type)
{
	if(id != "" && cityid != "" && type != "")
	{
		var processresult = function(result) {
			var responsetxt = document.getElementById("categorystatus");
			if(result == 0) {
                                if(responsetxt) {
                                    responsetxt.style.display = "none";
                                }
				var form = document.getElementById("sponsor");
				form.submit.disabled = true;
				var queue = document.getElementById("sponsorqueue");
				queue.style.display = "block";
				return 0;
			}else {
				if(responsetxt) {
					responsetxt.innerHTML = "Don't wait! There are only "+result+" spots available for this Park Bench!";
                                        responsetxt.style.display = "block";
				}
                                var queue = document.getElementById("sponsorqueue");
                                queue.style.display = "none";
                                var form = document.getElementById("sponsor");
                                form.submit.disabled = false;
				return 1;
			}
		}
		HTML_AJAX.grab("getCategoryStatus.php?id="+id+"&cityid="+cityid+"&type="+type,processresult);
		return false;
	} 
	// If we get here... they chose "Select"
        var form = document.getElementById("sponsor");
        form.submit.disabled = true;
        var queue = document.getElementById("sponsorqueue");
        queue.style.display = "none";
	var responsetxt = document.getElementById("categorystatus");
	responsetxt.style.display = "none";

}

/* Get the status of a username */
var usertype = ""; // int 1 or null
function getUsernameStatus(form,strstate,usertype) 
{
	var str = form.username.value;
	if(str && strstate)
	{
		if(str.length <= 3) {
		txt = document.getElementById("usernamemessage");
		txt.innerHTML = "Username too short";
		return false;
		}else if(str.length >= 15) {
                txt = document.getElementById("usernamemessage");
                txt.innerHTML = "Username too long";
		return false;
		}
		var spcallback = function(result) {	
			if(result == 1)
			{
				txt = document.getElementById("usernamemessage");
				if(txt) {
					txt.innerHTML = "That username is available!";
				}
				return true;
				/*r catc = document.getElementById("parkbench");
				if(catc) {
					var cati = form.parkbench.selectedIndex;
					var cat = form.parkbench[ cati ].value;
					if(cat != "") {
					}
				} else {
					form.submit.disabled = false;
				}*/	
				
			} else if(result == 2) {
                                txt = document.getElementById("usernamemessage");
                                txt.innerHTML = "INVALID username! Please only alphanumerical values and underscores (_)";
				
			} else {
				txt = document.getElementById("usernamemessage");
				txt.innerHTML = "Sorry, that username is not available.";
				
			}
		}
		HTML_AJAX.grab("getUsernameStatus.php?u="+str+"&st="+strstate+"&type="+usertype,spcallback);
	} 
}

function changePassword(userid)
{
	var form = document.getElementById("changepasswordform");
        var str1 = form.currpass.value;
	var str2 = form.newpass.value;
        if(str1 && str2 && userid)
        {
	alert(userid);
                if(str2.length <= 3) {
                txt = document.getElementById("changepasswordmessage");
                txt.innerHTML = "Password too short";
                return false;
                }else if(str2.length >= 15) {
                txt = document.getElementById("changepasswordmessage");
                txt.innerHTML = "Password too long";
                return false;
                }
                var spcallback = function(result) {
                        if(result == 1)
                        {
                                txt = document.getElementById("changepasswordmessage");
                                if(txt) {
                                        txt.innerHTML = "Password successfully changed.";
                                }
                                return true;

                        } else {
                                txt = document.getElementById("changepasswordmessage");
                                txt.innerHTML = "Invalid Password.";
				return false;
                        }
                }
                HTML_AJAX.grab("/changePassword.php?uid="+userid+"&st1="+str1+"&st2="+str2,spcallback);
        }
}


function ajaxAddToQueue(form)
{
        emailVal = form.emailaddressq.value;
        var catid = document.getElementById("parkbench");
	if(typeof(catid) == "undefined" || !catid) catid = 1;
        var id = catid.options[document.getElementById("parkbench").selectedIndex].value;

        var aqcallback = function(result) {
                if(result == 1) {
                        // Show message
                        var spNode = document.getElementById("becomeSponsor");
                        spNode.innerHTML = "Thank you for your interest in becoming an Agent Sponsor. You will receive an email when a spot opens up.";
                } else {
                        // Most likely already exists
                        var spNode = document.getElementById("becomeSponsor");
                        spNode.innerHTML = "Sorry, but it appears that email address is already in our queue.";
                }
        }
        HTML_AJAX.grab("ajaxNotifyQueue.php?addNew="+emailVal+"&id="+id,aqcallback);
}

/* Function to toggle the abuse form on and off */
function toggleAbuseForm(id,link) {
	// Turn it off
	var effectnodename = "abuse"+id;
	var txtnoded = document.getElementById("abuse"+id);
	if(txtnoded) {
		if(txtnoded.style.display == "block") {
			$('#'+effectnodename).slideUp(300);
			txtnoded.style.display = "none";
			//node.innerHTML = "";
			return;
		} else {
                      $('#'+effectnodename).slideDown(300);		
		      txtnoded.style.display = "block";
		}
	}
	
	/*
	var cb = function(response) {
		if(response != "") {
			var effectnodename = "abuse"+id;
			var txtnode = document.getElementById("abuse"+id);
			txtnode.innerHTML = response;
			$('#'+effectnodename).corner();
			$('#'+effectnodename).fadeIn('slow');
			txtnode.style.display = "block";
		}
	}*/
	
	// Send the request
	//HTML_AJAX.grab("reportAbuse.php?id="+id+"&getform=1&postlink="+link,cb);
	//HTML_AJAX.replace("abuse"+id,"reportAbuse.php?id="+id+"&getform=1&postlink="+link);
	$("#abuse"+id).load("/reportAbuse.php?id="+id+"&getform=1&postlink="+link);
	return;
}

function submitForm(form,responseId) {
	if(form) {
		var options = {
			target: '#'+responseId,
			url: form.action
		};
		$('#'+form.name).ajaxSubmit(options);
	}
}
//
//  Examples - Unremark if you want to see how this code works
/*
var expdate = new Date ();
FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000)); // 24 hrs from now 
SetCookie ("ccpath", "http://www.hidaho.com/colorcenter/", expdate);
SetCookie ("ccname", "hIdaho Design ColorCenter", expdate);
SetCookie ("tempvar", "This is a temporary cookie.");
SetCookie ("ubiquitous", "This cookie will work anywhere in this domain",null,"/");
SetCookie ("paranoid", "This cookie requires secure communications",expdate,"/",null,true);
SetCookie ("goner", "This cookie must die!");
document.write (document.cookie + "<br>");
DeleteCookie ("goner");
document.write (document.cookie + "<br>");
document.write ("ccpath = " + GetCookie("ccpath") + "<br>");
document.write ("ccname = " + GetCookie("ccname") + "<br>");
document.write ("tempvar = " + GetCookie("tempvar") + "<br>");
*/
//
//  Cookie Functions -- "Night of the Living Cookie" Version (25-Jul-96)
//
//  Written by:  Bill Dortch, hIdaho Design <bdortch@hidaho.com>
//  The following functions are released to the public domain.
//
//  This version takes a more aggressive approach to deleting
//  cookies.  Previous versions set the expiration date to one
//  millisecond prior to the current time; however, this method
//  did not work in Netscape 2.02 (though it does in earlier and
//  later versions), resulting in "zombie" cookies that would not
//  die.  DeleteCookie now sets the expiration date to the earliest
//  usable date (one second into 1970), and sets the cookie's value
//  to null for good measure.
//
//  Also, this version adds optional path and domain parameters to
//  the DeleteCookie function.  If you specify a path and/or domain
//  when creating (setting) a cookie**, you must specify the same
//  path/domain when deleting it, or deletion will not occur.
//
//  The FixCookieDate function must now be called explicitly to
//  correct for the 2.x Mac date bug.  This function should be
//  called *once* after a Date object is created and before it
//  is passed (as an expiration date) to SetCookie.  Because the
//  Mac date bug affects all dates, not just those passed to
//  SetCookie, you might want to make it a habit to call
//  FixCookieDate any time you create a new Date object:
//
//    var theDate = new Date();
//    FixCookieDate (theDate);
//
//  Calling FixCookieDate has no effect on platforms other than
//  the Mac, so there is no need to determine the user's platform
//  prior to calling it.
//
//  This version also incorporates several minor coding improvements.
//
//  **Note that it is possible to set multiple cookies with the same
//  name but different (nested) paths.  For example:
//
//    SetCookie ("color","red",null,"/outer");
//    SetCookie ("color","blue",null,"/outer/inner");
//
//  However, GetCookie cannot distinguish between these and will return
//  the first cookie that matches a given name.  It is therefore
//  recommended that you *not* use the same name for cookies with
//  different paths.  (Bear in mind that there is *always* a path
//  associated with a cookie; if you don't explicitly specify one,
//  the path of the setting document is used.)
//  
//  Revision History:
//
//    "Toss Your Cookies" Version (22-Mar-96)
//      - Added FixCookieDate() function to correct for Mac date bug
//
//    "Second Helping" Version (21-Jan-96)
//      - Added path, domain and secure parameters to SetCookie
//      - Replaced home-rolled encode/decode functions with Netscape's
//        new (then) escape and unescape functions
//
//    "Free Cookies" Version (December 95)
//
//
//  For information on the significance of cookie parameters, and
//  and on cookies in general, please refer to the official cookie
//  spec, at:
//
//      http://www.netscape.com/newsref/std/cookie_spec.html    
//
//******************************************************************
//
// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}
//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}
//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}
//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid.  If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
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 to delete a cookie. (Sets expiration date to start of epoch)
//    name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//
function DeleteCookie (name,path,domain) {
  if (GetCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}
/* combobox.js */
 // Usage:
 //  jvhead_addstmt("<script language='JavaScript' src='/jslib/combobox.js' type='text/javascript'></script>");
 //  jvhead_addstmt("<script language='JavaScript' src='/jslib/wddx/wddx.js' type='text/javascript'></script>");
 //
 // Function summary:
 //    combobox_dosubmit
 //    selectUnselectMatchingOptions
 //    selectMatchingOptions
 //    selectOnlyMatchingOptions
 //    unSelectMatchingOptions
 //    sortSelect
 //      after sort, you may wish to reattach ids since they are dropped during sorting...
 //       reapplyids: function(so) {
 //        for (var i=0; i<so.options.length; i++) {
 //          so.options[i].id = so.options[i].value;
 //        }
 //       },
 //    unselectAllOptions
 //    selectAllOptions
 //    moveSelectedOptions
 //    moveOneOptions
 //    addToSelectOptions (see sortSelect note above if sort is true here)
 //    deleSelectedOptions
 //    deleOptions
 //    copySelectedOptions
 //    moveAllOptions
 //    copyAllOptions
 //    swapOptions
 //    moveOptionUp
 //    moveOptionDown
 // ===================================================================
 // Author: Matt Kruse <matt@mattkruse.com>
 // WWW: http://www.mattkruse.com/
 // Extensions by: Frank Koenen <fkoenen@virtualmonet.com>
 //
 // NOTICE: You may use this code for any purpose, commercial or
 // private, without any further permission from the author. You may
 // remove this notice from your final code if you wish, however it is
 // appreciated by the author if at least my web site address is kept.
 //
 // You may *NOT* re-distribute this code in any way except through its
 // use. That means, you can include it in your product, or your web
 // site, or any other form where the code is actually being used. You
 // may not put the plain javascript up on your site for download or
 // include it in your javascript libraries for download. Instead,
 // please just point to my URL to ensure the most up-to-date versions
 // of the files. Thanks.
 // ===================================================================

 // -------------------------------------------------------------------
 //  Use this function on submits to gather selection items into wddx/array
 //  Call this function with two or three arguments: 
 //   1 :== the name of the hidden variable to store the wddx value into.
 //   2 :== the name of the multi-select widget that contains the values.
 //   3 :== only if selected in the list. [default=false]
 //  Also: make sure wddx/wddx.js is included!
 // -------------------------------------------------------------------
function combobox_dosubmit(hidden,selectObj,selected) {

 if ( ! arguments[2] ) selected=false;

 if ( hidden && selectObj ) {
  var myarr = new Array();
  var count=0;
  for ( var i=0;i<selectObj.length;i++ ) {
   if ( ( selected && selectObj[i].selected ) || ! selected ) {
    myarr[count++]= new combobox_wddxobject(selectObj[i].value,selectObj[i].text);
   }
  }

  var MySer = new WddxSerializer();
  hidden.value=MySer.serialize(myarr);
 
  return(true);
 }

}
function combobox_wddxobject(value,text) { this.value=value; this.text=text; }

 // -------------------------------------------------------------------
 // selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
 //  This is a general function used by the select functions below, to
 //  avoid code duplication
 // -------------------------------------------------------------------
 function selectUnselectMatchingOptions(obj,regex,which,only) {
         if (window.RegExp) {
                 if (which == "select") {
                         var selected1=true;
                         var selected2=false;
                         }
                 else if (which == "unselect") {
                         var selected1=false;
                         var selected2=true;
                         }
                 else {
                         return;
                         }
                 var re = new RegExp(regex);
                 for (var i=0; i<obj.options.length; i++) {
                         if (re.test(obj.options[i].text)) {
                                 obj.options[i].selected = selected1;
                                 }
                         else {
                                 if (only == true) {
                                         obj.options[i].selected = selected2;
                                         }
                                 }
                         }
                 }
         }
                 
 // -------------------------------------------------------------------
 // selectMatchingOptions(select_object,regex)
 //  This function selects all options that match the regular expression
 //  passed in. Currently-selected options will not be changed.
 // -------------------------------------------------------------------
 function selectMatchingOptions(obj,regex) {
         selectUnselectMatchingOptions(obj,regex,"select",false);
         }
 // -------------------------------------------------------------------
 // selectOnlyMatchingOptions(select_object,regex)
 //  This function selects all options that match the regular expression
 //  passed in. Selected options that don't match will be un-selected.
 // -------------------------------------------------------------------
 function selectOnlyMatchingOptions(obj,regex) {
         selectUnselectMatchingOptions(obj,regex,"select",true);
         }
 // -------------------------------------------------------------------
 // unSelectMatchingOptions(select_object,regex)
 //  This function Unselects all options that match the regular expression
 //  passed in. 
 // -------------------------------------------------------------------
 function unSelectMatchingOptions(obj,regex) {
         selectUnselectMatchingOptions(obj,regex,"unselect",false);
         }
         
 // -------------------------------------------------------------------
 // sortSelect(select_object)
 //   Pass this function a SELECT object and the options will be sorted
 //   by their text (display) values
 // -------------------------------------------------------------------
 function sortSelect(obj) {
         var o = new Array();
         for (var i=0; i<obj.options.length; i++) {
           o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
         }

         o = o.sort( 
                 function(a,b) { 
                   if ((a.text+"") < (b.text+"")) { return -1; }
                   if ((a.text+"") > (b.text+"")) { return 1; }
                   return 0;
                 } 
             );

         if ( ! o ) return;
         for (var i=0; i<o.length; i++) {
           obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
         }
 }

 // -------------------------------------------------------------------
 // unselectAllOptions(select_object)
 //  This function takes a select box and un-selects all options (in a 
 //  multiple select object).
 // -------------------------------------------------------------------
 function unselectAllOptions(obj) {
         for (var i=0; i<obj.options.length; i++) {
                 obj.options[i].selected = false;
                 }
         }
         
 // -------------------------------------------------------------------
 // selectAllOptions(select_object)
 //  This function takes a select box and selects all options (in a 
 //  multiple select object). This is used when passing values between
 //  two select boxes. Select all options in the right box before 
 //  submitting the form so the values will be sent to the server.
 // -------------------------------------------------------------------
 function selectAllOptions(obj) {
         for (var i=0; i<obj.options.length; i++) {
                 obj.options[i].selected = true;
                 }
         }
         
 // -------------------------------------------------------------------
 // moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
 //  This function moves options between select boxes. Works best with
 //  multi-select boxes to create the common Windows control effect.
 //  Passes all selected values from the first object to the second
 //  object and re-sorts each box.
 //  If a third argument of 'false' is passed, then the lists are not
 //  sorted after the move.
 //  If a fourth string argument is passed, this will function as a
 //  Regular Expression to match against the TEXT or the options. If 
 //  the text of an option matches the pattern, it will NOT be moved.
 //  It will be treated as an unmoveable option.
 //  You can also put this into the <SELECT> object as follows:
 //    onDblClick="moveSelectedOptions(this,this.form.target)
 //  This way, when the user double-clicks on a value in one box, it
 //  will be transferred to the other (in browsers that support the 
 //  onDblClick() event handler).
 //  this function returns the number of items moved.
 // -------------------------------------------------------------------
 function moveSelectedOptions(from,to) {

         var c=0;

         // Unselect matching options, if required
         if (arguments.length>3) {
             var regex = arguments[3];
             if (regex != "") {
               unSelectMatchingOptions(from,regex);
           }
         }

         // Move them over
         for (var i=0; i<from.options.length; i++) {
           var o = from.options[i];
           if (o.selected) {
             to.options[to.options.length] = new Option( o.text, o.value, false, false);
             c++;
           }
         }

         if ( c > 0 ) {
           // Delete them from original
           for (var i=(from.options.length-1); i>=0; i--) {
               var o = from.options[i];
               if (o.selected) {
                 from.options[i] = null;
             }
           }
           
           if ((arguments.length<3) || (arguments[2]==true)) {
              sortSelect(from);
              sortSelect(to);
           }
           
           from.selectedIndex = -1;
           to.selectedIndex = -1;
         }

         return c;
  }

 // -------------------------------------------------------------------
 // move one item from an option box, to another, given index.
 // -------------------------------------------------------------------
 function moveOneOptions(from,to,index) {
   addToSelectOptions(to,from.options[index].value,from.options[index].text,false);
   from.options[index] = null;
 }

 // -------------------------------------------------------------------
 // addToSelectOptions(select_object,value,text[,autosort(true/false)],[cleanvalues(true/false)])
 //  This function adds items from an options select box.
 // -------------------------------------------------------------------
 function addToSelectOptions(to,value,text,autosort,cleanvalues) {

    if ( typeof(cleanvalues) == 'undefined' ) cleanvalues=true;
    if ( typeof(autosort) == 'undefined' )    autosort=false;

    if ( cleanvalues ) {
     if ( value ) value=value.replace(/ +$/g,'');
     if ( text ) text=text.replace(/ +$/g,'');
     if ( ! text ) text=value;
     if ( text == '' || value == '' ) return;
    }

    // Add
    to.options[to.options.length] = new Option( text, value, false, false);

    if (autosort==true) sortSelect(to);

    to.selectedIndex = -1;

  }

 // -------------------------------------------------------------------
 // deleSelectedOptions(select_object)
 //  This function removes selected items from an options select box. Works best with
 //  onDblClick() event handler.
 //  this function returns the number of items deleted.
 // -------------------------------------------------------------------
 function deleSelectedOptions(from) {

         var c=0;
         // Delete them if they are selected.
         var ll=from.options.length;
         for (var i=(ll-1); i>=0; i--) {
                 var o = from.options[i];
                 if (o.selected) {
                    from.options[i] = null;
                    c++;
                 }
         }
         if ( c > 0 ) from.selectedIndex = -1;
         return c;
  }

 // -------------------------------------------------------------------
 // deleOptions(select_object)
 //  This function removes items from an options select box.
 // -------------------------------------------------------------------
 function deleOptions(from) {

         // Delete them
         var ll=from.options.length;
         for (var i=(ll-1); i>=0; i--) {
           var o = from.options[i];
           from.options[i] = null;
         }
         from.selectedIndex = -1;
  }

 // -------------------------------------------------------------------
 // copySelectedOptions(select_object,select_object[,autosort(true/false)])
 //  This function copies options between select boxes instead of 
 //  moving items. Duplicates in the target list are not allowed.
 // -------------------------------------------------------------------
 function copySelectedOptions(from,to) {
         var options = new Object();
         for (var i=0; i<to.options.length; i++) {
                 options[to.options[i].text] = true;
                 }
         for (var i=0; i<from.options.length; i++) {
                 var o = from.options[i];
                 if (o.selected) {
                         if (options[o.text] == null || options[o.text] == "undefined") {
                                 to.options[to.options.length] = new Option( o.text, o.value, false, false);
                                 }
                         }
                 }
         if ((arguments.length<3) || (arguments[2]==true)) {
                 sortSelect(to);
                 }
         from.selectedIndex = -1;
         to.selectedIndex = -1;
         }

 // -------------------------------------------------------------------
 // moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
 //  Move all options from one select box to another.
 // -------------------------------------------------------------------
 function moveAllOptions(from,to) {
         selectAllOptions(from);
         if (arguments.length==2) {
                 moveSelectedOptions(from,to);
                 }
         else if (arguments.length==3) {
                 moveSelectedOptions(from,to,arguments[2]);
                 }
         else if (arguments.length==4) {
                 moveSelectedOptions(from,to,arguments[2],arguments[3]);
                 }
         }

 // -------------------------------------------------------------------
 // copyAllOptions(select_object,select_object[,autosort(true/false)])
 //  Copy all options from one select box to another, instead of
 //  removing items. Duplicates in the target list are not allowed.
 // -------------------------------------------------------------------
 function copyAllOptions(from,to) {
         selectAllOptions(from);
         if (arguments.length==2) {
                 copySelectedOptions(from,to);
                 }
         else if (arguments.length==3) {
                 copySelectedOptions(from,to,arguments[2]);
                 }
         }

 // -------------------------------------------------------------------
 // swapOptions(select_object,option1,option2,[array_of_attributes_to_preserve])
 //  Swap positions of two options in a select list
 // Example: swapOptions(selectorobject,1,2,['Xcustom','style']);
 // -------------------------------------------------------------------
 function swapOptions(obj,i,j,preserveattributes) {
         var o = obj.options;
         var i_selected = o[i].selected;
         var j_selected = o[j].selected;

         if ( preserveattributes ) {
          var obji=new Object();
          var objj=new Object();
          for(var n=0;n<preserveattributes.length;n++){
           obji[preserveattributes[n]]=o[i].getAttribute(preserveattributes[n]);
           objj[preserveattributes[n]]=o[j].getAttribute(preserveattributes[n]);
          }
         }

         var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
         var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
         o[i] = temp2;
         o[j] = temp;
         o[i].selected = j_selected;
         o[j].selected = i_selected;

         if ( preserveattributes ) {
          for(var n=0;n<preserveattributes.length;n++){
           o[i].setAttribute(preserveattributes[n],objj[preserveattributes[n]]);
           o[j].setAttribute(preserveattributes[n],obji[preserveattributes[n]]);
          }
         }
 }
         
 // -------------------------------------------------------------------
 // moveOptionUp(select_object,[array_of_attributes_to_preserve])
 //  Move *selected* option in a select list up one
 // Example: moveOptionUp(selectorobject,['Xcustom','style']);
 // -------------------------------------------------------------------
 function moveOptionUp(obj,preserveattributes) {
         // If > 1 option selected, do nothing
         var selectedCount=0;
         for (i=0; i<obj.options.length; i++) {
                 if (obj.options[i].selected) {
                         selectedCount++;
                         }
                 }
         if (selectedCount > 1) {
                 return;
                 }
         // If this is the first item in the list, do nothing
         var i = obj.selectedIndex;
         if (i == 0) {
                 return;
                 }
         swapOptions(obj,i,i-1,preserveattributes);
         obj.options[i-1].selected = true;
         }

 // -------------------------------------------------------------------
 // moveOptionDown(select_object,[array_of_attributes_to_preserve])
 //  Move *selected* option in a select list down one
 // Example: moveOptionDown(selectorobject,['Xcustom','style']);
 // -------------------------------------------------------------------
 function moveOptionDown(obj,preserveattributes) {
         // If > 1 option selected, do nothing
         var selectedCount=0;
         for (i=0; i<obj.options.length; i++) {
                 if (obj.options[i].selected) {
                         selectedCount++;
                         }
                 }
         if (selectedCount > 1) {
                 return;
                 }
         // If this is the last item in the list, do nothing
         var i = obj.selectedIndex;
         if (i == (obj.options.length-1)) {
                 return;
                 }
         swapOptions(obj,i,i+1,preserveattributes);
         obj.options[i+1].selected = true;
         }
function PhotoBlogValidate() { }

PhotoBlogValidate.prototype.validate = validatePBform;
PhotoBlogValidate.prototype.showError = showPBerror;
PhotoBlogValidate.prototype.hideError = hidePBerror;

function validatePBform() {
       var error = "";

       if ( document.photobloguploadform.fname.value == "" )
         error += "<br/>&bull; Missing Firstname information.";

       if ( document.photobloguploadform.lname.value == "" )
         error += "<br/>&bull; Missing Lastname information.";

       if ( document.photobloguploadform.email.value == "" )
         error += "<br/>&bull; Missing Email information.";

       if ( document.photobloguploadform.fileupload1.value == "" )
         error += "<br/>&bull; Please provide an image to upload.";

       if ( document.photobloguploadform.phototitle.value == "" )
         error += "<br/>&bull; Missing Photo Title information.";

       if ( document.photobloguploadform.photodescription.value == "" )
         error += "<br/>&bull; Missing Photo Caption information.";

       if ( !document.photobloguploadform.accept_terms.checked )
         error += "<br/>&bull; You must agree to the Terms of Use.";

       if ( error != '' )
       {
          // Change the error string to a one liner to save vertical space...
                    error = "<br />You must fill out all fields and agree to the terms of use";
                    showPBerror(error);
                    return false;
       }

       return true;
}

function hidePBerror() {
	var d = document.getElementById("photoblogerror");
	d.innerHTML = "&nbsp;";
}

function showPBerror(str) {
	   document.getElementById("photoblogmessage").innerHTML = "";
	   var d = document.getElementById("photoblogerror");
	   d.innerHTML = str;
	   setTimeout("hidePBerror()",4000);
}

function PhotoBlogBox() { }

PhotoBlogBox.prototype.getNextPhoto = getNextPhoto;
PhotoBlogBox.prototype.getPrevPhoto = getPrevPhoto;

function getNextPhoto() {
	$("#randomphotohere").load("/photoblogajax.php?command=getnextphoto");
}
function getPrevPhoto() {
        $("#randomphotohere").load("/photoblogajax.php?command=getprevphoto");
}

function pbsendToSelection()
{
        var state = document.getElementById("stateselect");
        var city = document.getElementById("cityselect");
        var stateindex = document.getElementById("stateselect").selectedIndex;
        var cityindex = document.getElementById("cityselect").selectedIndex;
        var selectedState = state.options[stateindex].text;
        var selectedCity = city.options[cityindex].text;
        if(selectedCity == "--Select City--") return false;
        selectedState = selectedState.toLowerCase();
        selectedCity = selectedCity.toLowerCase();
        selectedState = selectedState.replace(" ","");
        selectedCity = selectedCity.replace(" ","");
        selectedState = selectedState.replace(".","");
        selectedCity = selectedCity.replace(".","");
        var nlocation = "http://"+selectedCity+"."+selectedState+"blogpage.com";
       parent.window.location = nlocation;
}


function showPhotoBlogUploadFrame(boolFormResult) 
{
	if(boolFormResult) {
		var iframe = document.getElementById("pbuploadiframe");
		iframe.style.height = 65;
		iframe.style.width = 340;
		iframe.style.border = "1px solid #888";
		$("#pbuploadiframe").fadeIn(500);
		return true;
	} else {
		return false;
	}
}

/*
 * Old version.
 *
function pbgetpage(page)
{
        var pbdiv = "photoblogcontent";
        if(page) {
                $j("#photoblogcontent").fadeOut(400);
                var t = document.getElementById(pbdiv);
                t.innerHTML = "";
                //HTML_AJAX.replace(pbdiv,"/getPhotoBlogContent.php?page="+page);
                $j("#photoblogcontent").fadeIn(400);
        }
}
*/
var slideshow = 0;
function pbgetpage(page,slideshow)
{
        var pbdiv = "photoblogcontent";
        if(page) {
                $("#photoblogcontent").fadeOut(400);
                var t = document.getElementById(pbdiv);
                t.innerHTML = "";
		if(slideshow) {
			$("#photoblogcontent").load("/getPhotoBlogContent.php?page="+page+"&slideshow=1"); 
		} else {
			$("#photoblogcontent").load("/getPhotoBlogContent.php?page="+page);
		}
                $("#photoblogcontent").fadeIn(400);
        }
}


function pbtoggletab(tab)
{
        var link = "";
        var text = "";
        if(tab) {
                var p = document.getElementById("photoblogtabs");
                var tabs = p.getElementsByTagName("span");
                for(var i=0;i<tabs.length;i++) {
                        var thistab = tabs[i];
                        var thistabtext = document.getElementById("pbtab"+i+"text");
                        var thistablink = document.getElementById("pbtab"+i+"link");
                        if(thistab.getAttribute("id") == tab) {
                                thistabtext.style.display = "block";
                                thistablink.style.display = "none";
                        } else {
                                thistablink.style.display = "block";
                                thistabtext.style.display = "none";
                        }
                }
        }
}


function pbnavigate(direction)
{
        if(direction == 'next') {

                        var thispage = pbgetpagenum();
                        var p = document.getElementById("photoblogtabs");
                        var tabs = p.getElementsByTagName("span");
                        var newpagenum = (thispage - 1);
                        if(pbpage_exists(newpagenum) == null) {
                                newpagenum = tabs.length-1;
                        }
                        var tmp = document.getElementById("pbtab"+newpagenum);
                        var divs = tmp.getElementsByTagName("div");
                        for(var i=0;i<divs.length;i++) {
                                if(i == 1) break;
                                var newpage = divs[i].getAttribute("id");
                        }
                        var newtab = "pbtab"+newpagenum;
                        pbgetpage(newpage);
                        pbtoggletab(newtab);

        } else if(direction == 'previous') {

                        var thispage = pbgetpagenum();
                        var p = document.getElementById("photoblogtabs");
                        var tabs = p.getElementsByTagName("span");
                        var newpagenum = (thispage + 1);
                        if(pbpage_exists(newpagenum) == null) {
                                newpagenum = 0;
                        }
                        var tmp = document.getElementById("pbtab"+newpagenum);
                        var divs = tmp.getElementsByTagName("div");
                        for(var i=0;i<divs.length;i++) {
                                if(i == 1) break;
                                var newpage = divs[i].getAttribute("id");
                        }
                        var newtab = "pbtab"+newpagenum;
                        pbgetpage(newpage);
                        pbtoggletab(newtab);

        }
	return false;
}


function pbpage_exists(page)
{
                var p = document.getElementById("photoblogtabs");
                var tabs = p.getElementsByTagName("span");
                for(var i=0;i<tabs.length;i++) {
                        if(i == page) {
                                return i;
                        }
                }
                return null;
}


function pbgetpagenum()
{
                var p = document.getElementById("photoblogtabs");
                var tabs = p.getElementsByTagName("span");
                for(var i=0;i<tabs.length;i++) {
                        var thistabtext = document.getElementById("pbtab"+i+"text");
                        if(thistabtext.style.display == "block") {
                                return i;
                        }
                }
}

function pbswaptab(id,status)
{
        var tab = document.getElementById(id);
        if(tab) {
                switch(status) {
                        case "on":
                                tab.style.background = 'url(/images/pbtabm_over.gif)';
                                tab.style.backgroundPosition = 'center center';
                                tab.style.backgroundRepeat = 'no-repeat';
                        break;
                        case "off":
                                tab.style.background = 'url(/images/pbtab.gif)';
                                tab.style.backgroundPosition = 'center center';
                                tab.style.backgroundRepeat = 'no-repeat';
                        break;
                }
        }
}
