/*****************************************************
** MANHUNT JavaScript Library
** Author: Zachary Segal
** Version: 0.75
** Date: Jan. 31, 2008
** copyright MANHUNT 2008
*****************************************************/

// site wide javascript functions

//global variables
var clickable = true;

jQuery(document).ready(function(){
    if (jQuery.browser.msie == true && jQuery.browser.version == 6) {
        //alert('ie6 window fixes');
        try {
            if (window.name == 'manhunt_login') {
                // set window's initial state
                ie6PositionBottomBar();
                ie6MinWidth(955);
                
                // bind window resize actions
                jQuery(window).bind('resize',function() {
                    ie6PositionBottomBar();
                    ie6MinWidth(955);
                });
                
                // bind window scroll actions
                jQuery(window).bind('scroll',function() {
                    ie6PositionBottomBar();
                });
            }
            else {
                // set window's initial state
                ie6MinWidth(810);
                
                // bind window resize actions
                jQuery(window).bind('resize',function() {
                    ie6MinWidth(810);
                });
            }
        }        
        catch (e) {
            alert(mhDictionary.site.generalError);
        }
    }
    addGoogleTracking();
});

function ie6PositionBottomBar() {
    var windowHeight = jQuery(window).height()
    var scrollOffset = jQuery(window).scrollTop()
    var bottomBarHeight = 41
    var offset = windowHeight + scrollOffset - bottomBarHeight;
    
    jQuery('.bottomBar').css('top',offset);
    jQuery('.modalCurtainMain').css('top', scrollOffset);
    jQuery('.modalWindowContainer').css('top', scrollOffset + 100);
};

function ie6MinWidth(w) {
    var windowWidth = jQuery(window).width();
    if (windowWidth < (w+2)) {
        jQuery('body').width(w);
    }
    else {
        jQuery('body').width(windowWidth);
    }
};

function modalOpen(url, params, escapable, modalClass) {
    
    if (escapable == undefined) {
      escapable = true;
    }
    
    if (modalClass == undefined) {
      modalClass = 'modalWindow';
    }
    
    if (clickable == false) {
        return false;
    }
    clickable = false;

    // create DOM for modal dialog positioning element
    var modalWindowContainer = document.createElement('div');
    jQuery(modalWindowContainer).attr('id','modalWindowContainer');
    jQuery(modalWindowContainer).attr('class','modalWindowContainer');
    if (escapable == true) {
        jQuery(modalWindowContainer).click( function(event) { 
            if (event.target == this) {
                modalClose();
            }
        });
    }
    
    // create DOM for modal dialog
    var modalWindow = document.createElement('div');
    jQuery(modalWindow).attr('id','modalWindow');
    jQuery(modalWindow).attr('class', modalClass);
    
    // create DOM for curtain behind modal dialog
    var modalCurtain = document.createElement('div');
    jQuery(modalCurtain).attr('id','modalCurtain');
    jQuery(modalCurtain).attr('class','modalCurtainMain');
    jQuery(modalCurtain).html('&nbsp;');
    jQuery(modalCurtain).css('opacity',0);
    if (escapable == true) {
        jQuery(modalCurtain).click( function(event) { 
            if (event.target == this) {
                modalClose();
            }
        });
    }
    
    // turn scroll bars off for everthing behind modal curtain
    jQuery('*[mhscroll]').css('overflow','hidden');
    
    
    
    // open the modal window
    var url = url_for(url);
    jQuery.post(url, params, function(dialog) {
        
        // append created DOM to document body
        jQuery(modalWindow).html(dialog);
        jQuery(modalWindowContainer).append(modalWindow);
        jQuery('body').append(modalWindowContainer);
        jQuery('body').append(modalCurtain);
        
        if (jQuery.browser.msie == true && jQuery.browser.version == 6) {
            var scrollOffset = jQuery(window).scrollTop()
            jQuery('.modalCurtainMain').css('top', scrollOffset);
            jQuery('.modalWindowContainer').css('top', scrollOffset + 100);
            jQuery('select').css('visibility','hidden');
        }
        
        // widen the modal window if it is the account security question modal
        if (url.match('modalAsq') != null) {
            jQuery(modalWindow).css('width',600);
        }
        
        //jQuery('#modalWindow').corner('10px #111111');
        
        // fade in the modal dialog
        jQuery('#modalCurtain').fadeTo('medium', 0.7);
        jQuery('#modalWindow').fadeIn('medium', function() {
//            if (jQuery.browser.msie == false || jQuery.browser.version != 6) {
//                jQuery(this).corner('10px #080808');
//            }
            jQuery('#modalWindow input:first').focus();
            jQuery('#modalWindow #immediateFocus').focus();
            clickable = true
        });
        
    });

	// evidentaly js needs a little time before events off this trigger work.
	//setTimeout('jQuery("#modalWindow").trigger("modalWindowReady")', 150);
};

function modalClose() {
    
    if (clickable == false) {
        return false;
    }
    clickable = false;
    
    // fade out the modal dialog and remove the DOM from document
    jQuery('#modalCurtain').fadeTo('medium', 0);
    jQuery('#modalWindowContainer').fadeOut('medium', function() {
        if (jQuery.browser.msie == true && jQuery.browser.version == 6) {
            jQuery('select').css('visibility','visible');
        }
        
        jQuery('*[mhscroll]').css('overflow','auto');
        jQuery('#modalCurtain').remove();
        jQuery('#modalWindowContainer').remove();
        
        // re-enable form elements if login page
        if (jQuery('#loginusername').attr('disabled') == true) {
            jQuery('input').attr('disabled',false);
        }
        clickable = true;
    });
    
};

function checkUserLoginStatus() {
    // try and find the login cookie
    var loggedIn = false
    if (getCookie('MHLogin') != false) {
        loggedIn = true;
    }
    
    // if user is not logged in attempt to close window,
    // reloads the window if it can't be closed
    if (loggedIn == false) {
        window.close();
        window.location.reload();
    }
    
    // repeat window check in 0.5 second
    setTimeout('checkUserLoginStatus();',500);
};

function getCookie(name) {
    if (document.cookie.length > 0) {
        start = document.cookie.indexOf(name + "=");
        if (start != -1) { 
            start = start + name.length + 1;
            end = document.cookie.indexOf(";",start);
            if (end == -1) {
                end = document.cookie.length;
            }
            
            return unescape(document.cookie.substring(start,end));
        } 
    }
    
    return false;
};


var multichatWindow = {closed: true} ; // see: MHNET-2705: Clicking Chat link when chat window is already open doesn't bring window into focus
/**
 *@param destUid: only being used for chat. The user id of the user a person wants to chat with.
 *
 */
function setWindow(url, windowName, destUid) {
    if (clickable == false) {
        return false;
    }
    clickable = false;
    
    var newWindowSetting = "";
    switch (windowName) {
        case 'profile':     newWindowSetting = "width=800,height=700,"; break;
        case 'mail':        newWindowSetting = "width=940,height=640,"; break;
        case 'photo':       newWindowSetting = "width=1024,height=768,"; break;
        case 'chat':        newWindowSetting = "width=500,height=560,"; break;
        case 'help':        newWindowSetting = "width=950,height=665,"; break;
        case 'ccvHelp':     newWindowSetting = "width=300,height=400,"; break;
        case 'payOffline':  newWindowSetting = "width=600,height=600,"; break;
        case 'interac':     newWindowSetting = "width=820,height=360,"; break;
        case 'multichat':	newWindowSetting = "width=1024,height=860,"; break;
        case 'multichat_feedback': newWindowSetting = "width=512, height=750,"; break;
        default:            newWindowSetting = "width=800,height=600,"; break;
    }    

    switch (windowName) {
        case 'chat':    newWindowSetting += "resizable=yes,scrollbars=no,menubar=no,location=no,toolbar=no,titlebar=no,status=no,directories=no";
            windowName+=destUid; //By appending the destUid we make sure that the chat window name is unique for every chat window that opens. Otherwise the user's wouldn't be able to have more than one chat window open.
            break; 
        default: newWindowSetting += "resizable=yes,scrollbars=yes,menubar=no,location=no,toolbar=no,status=no";
    }
    
    
    if (windowName != 'ecpinfo') {
       var url = url_for(url);
    }
    if (windowName == 'multichat' && !multichatWindow.closed) { 
    	multichatWindow.focus(); 
    } else {
		if (jQuery.browser.msie == true && jQuery.browser.version == 8) {
			
			// IE8 pops up window UNDER the top one. very annoying.
			popupwindow = window.open(url, windowName, newWindowSetting);
		
		} else {
			
			if (window.opener != null) {
		        popupwindow = window.opener.open(url, windowName, newWindowSetting);
		    }
		    else {
		        popupwindow = window.open(url, windowName, newWindowSetting);
		    }
		}      
	    
	    if( popupwindow == null ){
	        alert(mhDictionary.site.enablePopUp);  
	    }
	    else{
	        popupwindow.focus();
	    }
	    if (windowName == 'multichat') 
	    	multichatWindow = popupwindow; 
    }
    clickable = true;
};

function removeWindow(win) {
    win.close();
};

function checkIfPopUpWindow(self, billing_url) {
    var parentWindow = null;
    
    try {
        parentWindow = window.opener.name;
    } catch (e) {
        parentWindow = false;
    }
    
	var url =  billing_url; //url_for(billing_url);
	
	if (jQuery.browser.msie == true && jQuery.browser.version == 8) {
	
		var openerWindow = null;
		var openerWindow2 = null;
		var openerWindow3 = null;
	
		try {
			openerWindow = window.opener;
		} catch(e) {
			openerWindow = null;
		}
		
		try {
			openerWindow2 = openerWindow.opener;
		} catch(e) {
			openerWindow2 = null;
		}
		
		try {
			openerWindow3 = openerWindow2.opener;
		} catch(e) {
			openerWindow3 = null;
		}		
		
		if(openerWindow && openerWindow.name == "manhunt_login") {
			openerWindow.location.assign(url);
			window.close();
	        return false;
		} else if(openerWindow2 && openerWindow2.name == "manhunt_login") {
			openerWindow2.location.assign(url);
			window.close();
	        return false;
		} else if(openerWindow3 && openerWindow3.name == "manhunt_login") {
			openerWindow3.location.assign(url);
			window.close();
	        return false;
		} 		
	
	} else if (parentWindow != false) {    
        window.opener.location.assign(url);
        window.close();
        return false;
    }
    
    return true;
};

/**
*  change the count of remaining character for standard regret message
*/
function countStdRegretCharacters(obj) {
    
    //declare variables
    var max = 500;
    var normalized_string = obj.value.replace(/\r/g,"");
    var characters_left = max - normalized_string.length;
    var tokenizedString = mhDictionary.site.charactersLeft;

    //stop user from inputting more then 250 characters 
    if(characters_left < 0) {
        obj.value = normalized_string.substr(0,max);
        characters_left = parseInt(max - obj.value.replace(/\r/g,"").length);
        alert(mhDictionary.profile.noCharacters);
    }
    
    //convert int to string for display purpose
    characters_left = mhDictionary.site.charactersLeft.replace(/%CHARACTERSLEFT%/,characters_left);
    
    //update div with message on webpage
    jQuery("#char_remain").html(characters_left);
    
};

/**
*  change the count of remaining character for profile text
*/
function countCharacters(obj) {
    
    //declare variables
    var max = 650;
    var normalized_string = obj.value.replace(/\r/g,"");
    var characters_left = max - normalized_string.length;
    var message_div = document.getElementById("char_remain")
    var tokenizedString = mhDictionary.site.charactersLeft;

    //stop user from inputting more then 650 characters 
    if(characters_left < 0) {
        obj.value = normalized_string.substr(0, max);
        characters_left = parseInt(max - obj.value.replace(/\r/g,"").length);
        alert(mhDictionary.profile.noCharacters);
    }
    
    //convert int to string for display purpose
    characters_left = mhDictionary.site.charactersLeft.replace(/%CHARACTERSLEFT%/,characters_left);
    
    //update div with message on webpage
    jQuery(message_div).html(characters_left);
    
};

/**
*  change the form fields when user changes their measurement type
*/
function changeView() {
        
    if (document.getElementById("unitType_english").checked) {
        jQuery("#endowmentMetric").hide();
        jQuery("#heightMetric").hide();
        
        jQuery("#endowmentEnglish").show();
        jQuery("#heightEnglish").show();
    }
    else {
        jQuery("#endowmentMetric").show();
        jQuery("#heightMetric").show();
        
        jQuery("#endowmentEnglish").hide();
        jQuery("#heightEnglish").hide();
    }
};

/**
*  setup the change measurement displays from english to metric
*/
function changeUnits() {    
    
    changeView();
    
    //change display with checkboxes
    jQuery("#unitType_english").click( function() { 
        //update english based on metric settings
        
        //load values from the metric input fields
        var metricHeight = jQuery("#height").val();
        var metricEndowmentLength = jQuery("#endowmentLength").val();
        var metricEndowmentGirth = jQuery("#endowmentGirth").val();
        
        //load english menus
        var englishHeightMenu = jQuery("#height_english").get(0);
        var englishEndowmentLengthMenu = jQuery("#endowmentLength_english").get(0);
        var englishEndowmentGirthMenu = jQuery("#endowmentGirth_english").get(0);
        
        //round values up if not a perfect conversion
        metricHeight = findMetricValue(metricHeight, englishHeightMenu);
        metricEndowmentLength = findMetricValue(metricEndowmentLength, englishEndowmentLengthMenu);
        metricEndowmentGirth = findMetricValue(metricEndowmentGirth, englishEndowmentGirthMenu);
        
        //remove metric value if it is out of range
        if(metricHeight == "") { jQuery("#height").val(""); }
        if(metricEndowmentLength == "") { jQuery("#endowmentLength").val(""); }
        if(metricEndowmentGirth == "") { jQuery("#endowmentGirth").val(""); }
        
        //set values from metric input fields to english menus
        jQuery("#height_english").val(metricHeight);
        jQuery("#endowmentLength_english").val(metricEndowmentLength);
        jQuery("#endowmentGirth_english").val(metricEndowmentGirth);
        
        changeView();
    });
    
    jQuery("#unitType_metric").click( function() {
        changeView();
    });
    
    //update metric fields when english option is choosen from its menu
    jQuery("#height_english").change( function() {
        jQuery("#height").val(this.value);
    });
    jQuery("#endowmentLength_english").change( function() {
        jQuery("#endowmentLength").val(this.value);
    });
    jQuery("#endowmentGirth_english").change( function() {
        jQuery("#endowmentGirth").val(this.value);
    });
    
};

function findMetricValue(v, menuOptions) {
    
    //no value in metric field, return blank space
    if (v == null || v == "" || parseInt(v) == 0) {
        return "";
    }
    
    
    //parse the value into an integer value
    v = parseInt(v);
    if (v < menuOptions[1].value) {
        return "";
    }
    
     //loop through menu options and find next highest acceptable metric value
    for (i = 0; i < menuOptions.length; i++) {
        if (v <= parseInt(menuOptions.options[i].value)) {
            v = menuOptions.options[i].value;
            return v;
        }
       }
    
    return "";
        
};

function viewProfilePic(obj, profileId) {
    
    var imageId = jQuery(obj).attr('photoid');
    
    if (imageId != undefined && imageId != null) {
        url = 'photo/view?imageId='+imageId+'&profileId='+profileId;
        setWindow(url, 'photo');
    }
    
};

/**
* get an photo's url by id and size
* 
* @param id int The id of the photo you want to load
* @param size string The size of the photo
* @param update string The id of the DOM element to update with the new photo
* @param url string The url the ajax function hits to get access to the photo 
**/
function getSingleImage(uid, id, size, update) {
    url = url_for('photo/ajaxGetPhoto');
    jQuery.post(url, {photoId:id, profileId:uid, photoSize:size}, function(data) { 
        try {
          var data = eval(data);
        }
        catch (e) {
          alert(mhDictionary.site.ajaxError);
          return false;
        }
        
        jQuery(update).css('backgroundImage','url('+data.url+')');
        jQuery(update).attr('photoid',data.id);
     //   jQuery(update).text(data.id);
    });
};

//Left Nav Functions
function flash(obj, color1, color2) {
    jQuery(obj).animate({color:color1}, 400, function() {
        jQuery(obj).animate({color:color2}, 400, function() {
            flash(obj, color1, color2);
        });
    });
};

function buildSearchSummary() {
    
    var searchParams = new Object();
    searchParams.Location = [];
    searchParams.Status = [];
    searchParams.Age = [];
    searchParams.Keywords = [];
    searchParams.Intos = [];
    searchParams.Availability = [];
    searchParams.Place = [];
    searchParams.Position = [];
    searchParams.Height = [];
    searchParams.CockLength = [];
    searchParams.CockGirth = [];
    searchParams.Build = [];
    searchParams.HairColor = [];
    searchParams.EyeColor = [];
    searchParams.Ethnicity = [];
    searchParams.Circumsized = [];
    searchParams.HIVStatus = [];
    
    var locations = [];
	var mySearchType = jQuery('#myLocSrchTyp').val();
	
	if (mySearchType == 'DISTANCE') {
		var rangeLocVal = jQuery('#range_location').val();
		var distVal = jQuery('#distanceSearch').attr('selectedIndex');
		var dd = jQuery('#distanceSearch option').eq(distVal).html();
		var tt = jQuery('#distanceMenu span').eq(0).html();
		var useLocStr = rangeLocVal + ": " + tt + " " + dd;
		locations.push(useLocStr);
	} else if (mySearchType == 'AREA') {
		jQuery('#areaSearchOptions select option:selected').each(function() {
      		locations.push(jQuery(this).html());
    	});
	} else if (mySearchType == 'MULTICITY') {
		jQuery('#multicitySearchOptions .acInput').each(function() {
      		locations.push(jQuery(this).val());
    	});
	}
    searchParams.Location = locations;
    
    // summarize the status option, online profiles only and profiles with pictures only
    if (jQuery('#onlineOnly').attr('checked')) {
        searchParams.Status.push(mhDictionary.search.onlineOnly);        
    }
    if  (jQuery('#picturesOnly').attr('checked')) {
        searchParams.Status.push(mhDictionary.search.picsOnly);
    }
    
    // summerize the keywords
    var keywords = jQuery('#keywords').val();
    if (keywords.length > 0) {
        searchParams.Keywords = keywords.split(' ');
        for (i=0; i < searchParams.Keywords.length; i++) {
            searchParams.Keywords[i] = htmlentities(searchParams.Keywords[i]);
        }
    }
    
    // summerize the different attribute and measurement groups
    var root = jQuery('.searchTabBox').each(function() {
    jQuery(this).children('div').find('input[type!=radio]').each(function() {
        var skip = false;
        if ((this.id == 'onlineOnly') || (this.id == 'picturesOnly')) {
            skip = true;
        }
        if (!skip) {
            var t = jQuery(this).filter(':checked').siblings('label').html();
            if (t != null) {
                var type = this.id.slice(0,this.id.indexOf('_'));
                var z = 'searchParams.' + type + '.push("'+t+'")';
                
                try {
                   eval(z);
                }
                catch (e) {
                    alert(mhDictionary.site.ajaxError);
                    return false;
                }
            }
        }
    });
    });
    // build the actual HTML code for the summary
    var summary = "";
    for (i in searchParams) {
        try {
            var searchArray = eval('searchParams.'+i);
        }
        catch (e) {
            alert(mhDictionary.site.ajaxError);
            return false;
        }
        
        summary += buildSectionSummary(searchArray, i);
    }
    
    // inject the summery into the DOM
    jQuery('.searchTabs a[name=summary]').show();
    jQuery('#summaryTab').html(summary);
};

function buildSectionSummary(a, l) {
    if (l == 'Age') {
        return buildMeasurementGroupSummary('#ageMin','#ageMax',l);
    }
    else if (l == 'Height') {
        return buildMeasurementGroupSummary('#minHeight','#maxHeight',l);
    } 
    else if (l == 'CockLength') {
        return buildMeasurementGroupSummary('#minCockLength','#maxCockLength',l);
    }
    else if (l == 'CockGirth') {
        return buildMeasurementGroupSummary('#minCockGirth','#maxCockGirth',l);
    }
    
    if (a.length == 0) {
        return "";
    }
    
    if (l == "Location") {
       var label = mhDictionary.location.locationLabel;
    } else {
	   var label = jQuery('#'+l+'Label').html();
    }
    return "<p>"+label+"</p> " + a.join(", ") + "<hr />";
};

function buildMeasurementGroupSummary(minId, maxId, l) {
    // get default english values
    var min = jQuery(minId + ' option:selected').text()
    var max = jQuery(maxId + ' option:selected').text()
    var unit = "";
    
    // get metric values if user is set to metric
    if (min == '' || min == undefined) {
      min = jQuery(minId).val();
    }
    if (max == '' || max == undefined) {
      max = jQuery(maxId).val();
    }
    
    // return an empty string if both min and max are empty
    if (min == "" && max == "") {
        return "";
    }
    
    // set combining words for the phrase
    var word = mhDictionary.search.between + " ";
    var ampersand = " " + mhDictionary.search.and + " ";
    if (max == "") {
        word = mhDictionary.search.over + " ";
        ampersand = " ";
    }
    if (min == "") {
        word = mhDictionary.search.under + " ";
        ampersand = " ";
    }
    
    // set the unit string for end of phrase
    if (jQuery(minId).get(0).type == 'text' || jQuery(maxId).get(0).type == 'text') {
        unit = "cm"
    }
    if (l == 'Age') {
        unit = mhDictionary.search.years;
    }
    
    var h = htmlentities(word + min + ampersand + max + " " + unit);
    var label = jQuery('#'+l+'Label').html();
    return "<p>"+label+"</p> <span>"+h+"</span><hr />";
};

function updateSearchRegion(obj) {
    alert(obj.value);
};

//Must get name of saved search we are currently editing.
function chkNameThenAjaxSaveSearchAs(obj) {
    var nameTmp = jQuery('#searchName').val();
    var name = jQuery.trim(nameTmp);
    
    var oldNameTmp = jQuery('#oldSearchName').val();
    var oldName = jQuery.trim(oldNameTmp);
    
    var keepGoin = true;
    var keepLooping = true;
    var oneMenuName = '';
    var x = jQuery('#MHmenuSearch ul li a').each(function(){
        if (!keepLooping) {
            return false;
        }
        oneMenuNameTmp = jQuery(this).html();
        oneMenuName = jQuery.trim(oneMenuNameTmp);
        if (name == oneMenuName) {
            keepGoin = confirm(mhDictionary.search.replaceSavedSearch.replace('%NAME%',name));
            keepLooping = false;
            if (keepGoin) {
                var linkToRemove = jQuery("#MHmenuSearch ul li a:contains('" + name + "')");
                linkToRemove.parent().remove();
                obj.savingOverExisting = 'true';
            }
            return false;
        }
    });
    if (!keepGoin) {
        return false;
    }
    //alert('new- ' + name);
    //alert('old- ' + oldName);
    //alert('match- ' + oneMenuName);
    
    // Editing the same search and not changing the name.
    //if ( (name == oneMenuName) && (name == oldName) ) {
    //  return ajaxSaveSearch(obj);
    //}
    // Editing the search and saving as a different name that already exists
    
    
    // Saving as a new name that doesn't yet exist. Keep the on
    //return ajaxSaveSearchAs(obj);
    
    
    // Editing the same search and not changing the name.
    if ( (name == oneMenuName) && (name == oldName) ) {
        return ajaxSaveSearch(obj);
    }
    // Editing the search and saving as a different name that already exists
    else if ( (name == oneMenuName) && (name != oldName) ) {
        return ajaxSaveSearchAs(obj, 'true', oneMenuName);
    }
    else {
    // Saving as a new name that doesn't yet exist. Keep the old saved search.
        return ajaxSaveSearchAs(obj, 'false', null);
    }
    
};

function ajaxSaveSearch(obj) {
    // disable button after single click
    if (clickable == false) {
        return false;
    }
    clickable = false;
    jQuery(obj).css('color','#888');
    jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_steel.png)');
    
    
    // get values from form elements
    var uid = jQuery('#uid').val();
    var tmp = jQuery('#searchName').val();
    var name = jQuery.trim(tmp);
    
    if (name.search(/</g) > -1 || name.search(/>/g) > -1) {
        alert(mhDictionary.search.badCharacterSavedSearchError);
        
        // re-enable save button
        jQuery(obj).css('color','#fff');
        jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_blue.png)');
        clickable = true;
        
        return false;
    }
    
    url = url_for('search/saveSearch');
    var saveOvrExistng = 'false';
    if (obj.savingOverExisting == 'true') {
        saveOvrExistng = 'true';
    }
    jQuery.post(url, {uid:uid, saveName:name, saveOver:saveOvrExistng}, function(data) {
        
        try {
            jsonData = eval(data);
        }
        catch (e) {
            alert(mhDictionary.site.ajaxError);
            
            // re-enable save button
            jQuery(obj).css('color','#fff');
            jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_blue.png)');
            clickable = true;
            return false;
        }
        
        
        if (jsonData.success != true) {
            try {
                jQuery('#errorMessage').html(jsonData.message);
            }
            catch (e) {
                alert(mhDictionary.site.ajaxError);
            }
            
            // re-enable save button
            jQuery(obj).css('color','#fff');
            jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_blue.png)');
            clickable = true;
            return false;
        }
        
        
        // remove the old saved search if user re-saved an old search
        if (jsonData.removeName != '') {
            var remSsName = decode_htmlentities(jsonData.removeName);
            var linkToRemove = jQuery("#MHmenuSearch ul li a:contains('" + remSsName + "')");
            linkToRemove.parent().remove();
        }
        
        
        // add the new saved search into the search menu
        name = name.replace(/</g, '');
        name = name.replace(/>/g, '');
        var escapedName = htmlentities(name);
        var link = "<li><a href='#' onclick='return sendSavedSearchForm(this)'>"+escapedName+"</a></li>"
        jQuery('#MHmenuSearch ul').append(link);
        
        
        // update search name in page title and side bar
        jQuery('.currentSearchDisplay').html(htmlentities(name));
        
        
        // close the modal window
        modalClose();
    });
    
    clickable = true;
    return false;
};

//TODO: If the name is different, then we clone the old one and create a new one.
function ajaxSaveSearchAs(obj, removeDuplicate, nameToRemove) {
    
    //alert('notice: ' + removeDuplicate);
    // disable button after single click
    if (clickable == false) {
        return false;
    }
    clickable = false;
    jQuery(obj).css('color','#888');
    jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_steel.png)');
    
    
    // get values from form elements
    var uid = jQuery('#uid').val();
    var name = jQuery('#searchName').val();
    
    
    if (name.search(/</g) > -1 || name.search(/>/g) > -1) {
        alert(mhDictionary.search.badCharacterSavedSearchError);
        
        // re-enable save button
        jQuery(obj).css('color','#fff');
        jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_blue.png)');
        clickable = true;
        
        return false;
    }
    
    url = url_for('search/saveSearch');
    var saveOvrExistng = 'false';
    if (obj.savingOverExisting == 'true') {
        saveOvrExistng = 'true';
    }
    var doCloneVar = 'true';
    //saveOvrExisting = 'false';
    jQuery.post(url, {uid:uid, saveName:name, saveOver:saveOvrExistng, doClone:doCloneVar}, function(data) {
        
        try {
            jsonData = eval(data);
        }
        catch (e) {
            alert(mhDictionary.site.ajaxError);
            
            // re-enable save button
            jQuery(obj).css('color','#fff');
            jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_blue.png)');
            clickable = true;
            return false;
        }
        
        
        if (jsonData.success != true) {
            try {
                jQuery('#errorMessage').html(jsonData.message);
            }
            catch (e) {
                alert(mhDictionary.site.ajaxError);
            }
            
            // re-enable save button
            jQuery(obj).css('color','#fff');
            jQuery(obj).css('background-image','url(' + assetDirectory + 'images/ui/fade_blue.png)');
            clickable = true;
            return false;
        }
        
        
        // remove the old saved search if user re-saved an old search
        //alert(saveOvrExistng);
        //alert(jsonData.removename);
        //if (removeDuplicate == 'true') {
        //  alert('oldName to remove- ' + nameToRemove);
        //    //var remSsName = decode_htmlentities(jsonData.removeName);
        //    var linkToRemove = jQuery("#MHmenuSearch ul li a:contains('" + nameToRemove + "')");
        //    linkToRemove.parent().remove();
        //}

        
        
        // add the new saved search into the search menu
        name = name.replace(/</g, '');
        name = name.replace(/>/g, '');
        var escapedName = htmlentities(name);
        //alert('add ' + escapedName);
        var link = "<li><a href='#' onclick='return sendSavedSearchForm(this)'>"+escapedName+"</a></li>"
        jQuery('#MHmenuSearch ul').append(link);
        
        
        // update search name in page title and side bar
        jQuery('.currentSearchDisplay').html(htmlentities(name));
        
        
        // close the modal window
        modalClose();
    });
    
    clickable = true;
    return false;
};

function sendSavedSearchForm(obj) {
    // submitRunSavedSearch -- the form name/id
    // savedSearchName -- the form's hidden field
    var ssName = decode_htmlentities(obj.innerHTML);
    
    jQuery('#name').val(ssName);
    jQuery('#submitRunSavedSearch').submit();
    
    return false;
};

function openCityListing() {
    var state = jQuery('#searchLocationState option:selected').val()
    jQuery('#searchCityRadio').attr('checked',true);
    jQuery('#searchCityRadio').parent().addClass('searchTypeSelected');
    jQuery('#searchLocationRegion').parent().removeClass('searchTypeSelected');
    modalOpen('search/modalCityList',{locId:state});
};

/**
 * zAccordian
 */ 
function slideAccordian(start, panelHeight) {
    
    var speed = 400;
    var clickable = true;
    
    // bind mousedown events to headers for changing panel display
    jQuery(".accordian dt").bind("click", function() {
        
        // initialize dom elements to show and hide
        var toShow = jQuery(this).next('dd');
        var toHide = jQuery(this).siblings('dd:visible');
        var iconShow = jQuery(this).siblings('dd:visible').prev('dt').children('img');
        var iconHide = jQuery(this).children('img');
        
        
        // if user click panel that is already visible, don't do anything
        if (toShow.css('display') == "block") {
            return false;
        }
        
        // check if an animation is currently going, if so don't allow click
        if (clickable == false) {
            return false;
        }
        clickable = false;
        
        // animate the expansion of panel to show, hide other panel with each step
        toShow.animate({height:panelHeight},{
            step: function(now) {
//                iconShow.css({opacity: now / panelHeight });
//                iconHide.css({opacity: 1 - (now / panelHeight) });
                toHide.css({ height : panelHeight - now });
            },
            duration: speed,
            complete: function() {
            	iconShow.attr('src', "/assets/manhunt/images/ui/orange_plus.jpg");
            	iconHide.attr('src', "/assets/manhunt/images/ui/orange_minus26.jpg");
                toHide.css({display:"none"});
                clickable = true;
            }
        });
    });
    // initialize display by opening the panel number of passed start value
    jQuery(".accordian dt").eq(start).click();
};

function sendWink(winkee, winkeeName) {
  ajaxUrl = url_for('wink');
  jQuery.post(ajaxUrl, {winkee:winkee, winkeeName:winkeeName}, function(data) {
    try {
      var data = eval(data);
    }
    catch (e) {
      alert(mhDictionary.site.ajaxError);
      return false;
    }
    
    modalUrl = 'winkMessage';
    modalOpen(modalUrl, {success:data.success, username:data.winkeeName});
  });
};

function url_for(url) {
    var path = window.location.pathname;
    
    if (path.match(".php") == ".php") {
      var regEx = new RegExp(/\/[^\/]*(\/?)/);
      var environment = regEx.exec(path);
      if (environment[1] != '/') {
        environment = environment[0] + '/';
      }
      else {
        environment = environment[0];
      }
      url = environment + url;
    }
    else {
      url = "/" + url;
    }
    
    return url;
};

function htmlentities(string) {
    var escapedString = string.replace(/&/g, '&amp;');
    escapedString = escapedString.replace(/>/g, '&gt;');
    escapedString = escapedString.replace(/</g, '&lt;');
    escapedString = escapedString.replace(/\'/g, '&#039;');
    escapedString = escapedString.replace(/\"/g, '&quot;');
    
    return escapedString;
};

function decode_htmlentities(string) {
    var decodeString = string.replace(/&amp;/g, '&');
    decodeString = decodeString.replace(/&gt;/g, '>');
    decodeString = decodeString.replace(/&lt;/g, '<');
    decodeString = decodeString.replace(/&#039;/g, '\'');
    decodeString = decodeString.replace(/&quot;/g, '"');
    
    return decodeString;
};

function isInt(str)
{
	var i = parseInt(str);
	if (isNaN(i)) {
	  return false;
	}
	i = i.toString();
	if (i != str) {
	  return false;
	}
	return true;
};

function addGoogleTracking() {
	var sc = document.createElement('script');
	sc.type = 'text/javascript';
	gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	sc.src = gaJsHost + 'google-analytics.com/ga.js';
	document.getElementsByTagName("head").item(0).appendChild(sc);
	_googleInterval = setInterval(activateGoogle,250);
}
function activateGoogle() {
	if(typeof _gat != 'undefined') {
		clearInterval(_googleInterval);
		var pageTracker = _gat._getTracker("UA-5700973-8");
		pageTracker._initData();
		pageTracker._trackPageview();
	}
}
function mktime() {
    // Get UNIX timestamp for a date  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/mktime
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: baris ozdil
    // +      input by: gabriel paderni
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FGFEmperor
    // +      input by: Yannoo
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: jakes
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Marc Palau
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: mktime(14, 10, 2, 2, 1, 2008);
    // *     returns 1: 1201871402
    // *     example 2: mktime(0, 0, 0, 0, 1, 2008);
    // *     returns 2: 1196463600
    // *     example 3: make = mktime();
    // *     example 3: td = new Date();
    // *     example 3: real = Math.floor(td.getTime()/1000);
    // *     example 3: diff = (real - make);
    // *     results 3: diff < 5
    // *     example 4: mktime(0, 0, 0, 13, 1, 1997)
    // *     returns 4: 883609200
    // *     example 5: mktime(0, 0, 0, 1, 1, 1998)
    // *     returns 5: 883609200
    // *     example 6: mktime(0, 0, 0, 1, 1, 98)
    // *     returns 6: 883609200
    var no=0, i = 0, ma=0, mb=0, d = new Date(), dn = new Date(), argv = arguments, argc = argv.length;

    var dateManip = {
        0: function(tt){ return d.setHours(tt); },
        1: function(tt){ return d.setMinutes(tt); },
        2: function(tt){ var set = d.setSeconds(tt); mb = d.getDate() - dn.getDate(); return set;},
        3: function(tt){ var set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - dn.getFullYear(); return set;},
        4: function(tt){ return d.setDate(tt+mb);},
        5: function(tt){
            if (tt >= 0 && tt <= 69) {
                tt += 2000;
            }
            else if (tt >= 70 && tt <= 100) {
                tt += 1900;
            }
            return d.setFullYear(tt+ma);
        }
        // 7th argument (for DST) is deprecated
    };

    for( i = 0; i < argc; i++ ){
        no = parseInt(argv[i]*1);
        if (isNaN(no)) {
            return false;
        } else {
            // arg is number, let's manipulate date object
            if(!dateManip[i](no)){
                // failed
                return false;
            }
        }
    }
    for (i = argc; i < 6; i++) {
        switch(i) {
            case 0:
                no = dn.getHours();
                break;
            case 1:
                no = dn.getMinutes();
                break;
            case 2:
                no = dn.getSeconds();
                break;
            case 3:
                no = dn.getMonth()+1;
                break;
            case 4:
                no = dn.getDate();
                break;
            case 5:
                no = dn.getFullYear();
                break;
        }
        dateManip[i](no);
    }

    return Math.floor(d.getTime()/1000);
}
function is_array( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
    // +   bugfixed by: Manish
    // +   improved by: Onno Marsman
    // %        note 1: In php.js, javascript objects are like php associative arrays, thus JavaScript objects will also
    // %        note 1: return true
    // *     example 1: is_array(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: is_array('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 3: true
    // *     example 4: is_array(function tmp_a(){this.name = 'Kevin'});
    // *     returns 4: false
 
    var key = '';
 
    if (!mixed_var) {
        return false;
    }
 
    if (typeof mixed_var === 'object') {
 
        if (mixed_var.hasOwnProperty) {
            for (key in mixed_var) {
                // Checks whether the object has the specified property
                // if not, we figure it's not an object in the sense of a php-associative-array.
                if (false === mixed_var.hasOwnProperty(key)) {
                    return false;
                }
            }
        }
 
        // Uncomment to enable strict JavsScript-proof type checking
        // This will not support PHP associative arrays (JavaScript objects), however
        // Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
        //
        //  if (mixed_var.propertyIsEnumerable('length') || typeof mixed_var.length !== 'number') {
        //      return false;
        //  }
 
        return true;
    }
 
    return false;
}

jQuery.fn.outerHTML = function() {
	return $('<div></div>').append( this.clone() ).html();
} 

// thanks: http://weblogs.asp.net/skillet/archive/2006/03/23/440940.aspx
function dumpObj(obj, name, indent, depth) {
	var MAX_DUMP_DEPTH = 10;
	if (obj == undefined) {
		return "Can't continue.  obj is undefined.";
	}
	if (name == undefined) {
		name = 'Undefined.';
	}
	if (indent == undefined) {
		indent = '---';
	}
	if (depth == undefined) {
		depth = MAX_DUMP_DEPTH;
	}
	if (depth > MAX_DUMP_DEPTH) {
		 return indent + name + ": <Maximum Depth Reached>\n";
	}
	if (typeof obj == "object") {
		var child = null;
		var output = indent + name + "\n";
		indent += "\t";
		for (var item in obj)
		{
			try {
			 	  child = obj[item];
			} catch (e) {
			 	  child = "<Unable to Evaluate>";
			}
			if (typeof child == "object") {
			 	  output += dumpObj(child, item, indent, depth + 1);
			} else {
			 	  output += indent + item + ": " + child + "\n";
			}
		 }
		 return output;
  } else {
		 return obj;
  }
}