var MM_contentVersion = 4;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	    for (var i = 0; i < words.length; ++i)
	    {
		if (isNaN(parseInt(words[i])))
		continue;
		var MM_PluginVersion = words[i]; 
	    }
	var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
} else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
   && (navigator.appVersion.indexOf("Win") != -1)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
	document.write('</SCR' + 'IPT\> \n');
}

function getFlash(width, height, file, loop, alternate, classid, secure) {
	var code_base;
	if (secure == 'true') {
		code_base = 'https';
	} else {
		code_base = 'http';
	}
	if (MM_FlashCanPlay) {
		var oeTags = '<OBJECT CLASSID="' + classid + '"'
         + 'WIDTH="' + width + '" HEIGHT="' + height + '"'
         + 'CODEBASE="' + code_base + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'
         + '<PARAM NAME="MOVIE" VALUE="' + file + '">'
         + '<PARAM NAME="PLAY" VALUE="true">'
         + '<PARAM NAME="LOOP" VALUE="' + loop + '">'
         + '<PARAM NAME="QUALITY" VALUE="high">'
         + '<PARAM NAME="MENU" VALUE="false">'
         + '<EMBED SRC="' + file + '"'
         + 'WIDTH="' + width + '" HEIGHT="' + height + '"'
         + 'PLAY="true"'
         + 'LOOP="' + loop + '"'
         + 'QUALITY="high"'
         + 'MENU="false"'
         + 'TYPE="application/x-shockwave-flash"'
         + 'PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash">'
         + '</EMBED>'
         + '</OBJECT>';
		document.write(oeTags);
	} else {
		var alternateContent = '<IMG SRC="' + alternate + '" HEIGHT="' + height + '" WIDTH="' + width + '" BORDER="0">'
		document.write(alternateContent);
	}
}

var imagepopup;
var otherpopup;
function popupView(url, features, popup_type) {
	switch (popup_type) {
		case 'image':
		if (!imagepopup || imagepopup.closed) {
	  		imagepopup = window.open(url,'imagepopup',features);
		} else {
			imagepopup.close();
		    imagepopup = window.open(url, 'imagepopup', features);
		}
		break;
		
		case 'other':
		if (!otherpopup || otherpopup.closed) {
	  		otherpopup = window.open(url,'otherpopup',features);
		} else {
			otherpopup.close();
		    otherpopup = window.open(url, 'otherpopup', features);
		}
		break;
		
		default:
		return false;
		break;
	}	
}

function loadLink(method, region, cat, resource, city) {
	var r;
	if (region == '') {
		return false;
	}
    r = '/location/' + method + '/' + region + '/' + cat;
	if (resource) {
		r = r + '/' + resource;
	}
	if (city) {
		r = r + '?city=' + city;
	} else {
		r = r + '/';
	}
    document.location.href = r;
}

function setUrl(path, dest) {
	if (dest != '') {
		document.location.href = path + dest;
	}
}

function loadGlobalResourceLink(resource_name, cat) {
	var r;
	r = '/' + resource_name + '/' + cat + '/';
	document.location.href = r;
}

function logClick(evnt, campaign_id) {
    var left = true;
    if ((evnt) && evnt.which) {
        if (evnt.which != 1) {
            left = false;
        }
    }
    else if (event && event.button) {
        if (event.button != 1) {
            left = false;
        }
    }
    if (left) {
		var img = new Image();
		img.src = "/ad/log/" + campaign_id + "/";
    }   
}


function logListingClick(evnt, lid, type, tid1, tid2) {
	var left = true;
    if ((evnt) && evnt.which) {
        if (evnt.which != 1) {
            left = false;
        }
    }
    else if (event && event.button) {
        if (event.button != 1) {
            left = false;
        }
    }
    if (left) {
		var img = new Image();
		img.src = "/listing/log_stat/" + lid + "?type=" + type + "&tid1=" + tid1 + "&tid2=" + tid2;
    }   
}

var cap_incr = 0;
function swapCaptcha(lid) {
	var img = new Image(); 
	img_src = '/captcha/create';
	if (lid) {
		img_src += '/'+lid;
	}
	img_src += '?cap_incr='+cap_incr;
	img.src=img_src;
	$('#captcha').attr('src', img.src);
	cap_incr += 1;
}

function myRnetReg() {
	subWindow = window.open("/user/signup?p=1", "otherpopup", "height=600,width=700");
}

function setTab(tab_id) {
	$('#subNav'+menu_tab).hide();
	$('#subNav'+tab_id).show();
	menu_tab = tab_id;
}

function setPopupBackground(ele_hide, ele_show) {
	$(ele_hide).hide();
	$(ele_show).show();
	$('.iframe_wrapper').height($('#popupBackground').height()); 
	$('.iframe_wrapper').width($('#popupBackground').width());
}

function switchFinder(tab) {
	var tabBox = 'findhi' + tab.substring(0,1).toUpperCase() + tab.substring(1,tab.length);
	$('#findhiCare').hide();
	$('#findhiActive').hide();
	$('#findhiServices').hide();
	$('#findhiVip').hide();
	$('#findhiVipIntro').hide();
	$('#'+tabBox).show();
	$('#findhi a').removeClass('selected');
	$('#'+tab+' a:first-child').addClass('selected');
	$('#findhi').css('backgroundPosition', '-0px -52px');
}

function setR(r, msg) {
	if (!confirm('You must be logged in to ' + msg + '. Click ok to sign in or create an account. It only takes a minute!')) {
    	return false;
   	}
   	$("#popupBackground").show().centerInClient();
	if ($.browser.msie) {
		$('.iframe_wrapper').show();
		$('.iframe_wrapper').height($('#popupBackground').height()); 
	   	$('.iframe_wrapper').width($('#popupBackground').width());
	}
   	$('#signinr').val(r);
   	$('#popup_signupr').val(r);
}

function formatDate(ts) {
	var month=new Array(12);
	month[0]="Jan";
	month[1]="Feb";
	month[2]="Mar";
	month[3]="Apr";
	month[4]="May";
	month[5]="June";
	month[6]="July";
	month[7]="Aug";
	month[8]="Sept";
	month[9]="Oct";
	month[10]="Nov";
	month[11]="Dec";
	
	var d = new Date();
	d.setTime(ts);
	var date_string = month[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear() + ' ';
	var hours = d.getHours();
	var ampm;
	var min;
	if (hours > 12) {
	  hours = hours % 12;
	  ampm = 'pm';
	} else if(hours < 12) {
	  ampm = 'am';
	  if (hours == 0) {
	    hours = 12;
	  }
	} else {
		ampm = 'pm';
	}
	date_string += hours + ':';
	min = d.getMinutes();
	date_string += (min < 10) ? '0' + min : min;
	date_string += ' ' + ampm;
	return date_string;
}

var editing, editobj, editorg, rurl, classorg;

function editReq(obj, url) {
    if (!editing) {
        editing = true;
		$.ajax({
		    url: url,
		    type: 'POST',
		    dataType: 'xml',
		    timeout: 5000,
		    error: function(){
		        alert('Error loading XML document');
		    },
		    success: function(xml){
		        alert('called controller');
		    },
			complete: function(xml){
				alert('complete');
			}
		});
	editing = false;
    }
}

function editPart(action, element, part, html, error, onsubmit_method) {
	var form_html = '<form id="ajax-form" action="' + action + '"><input type="hidden" name="updated" value="1" />';
	if (part) {
		form_html += '<input type="hidden" name="part" value="' + part + '" />';
	}
	if (html) {
		form_html += html;
	}
	form_html += '<div class="topspace"><input id="ajax-save" class="btnAction" style="margin-bottom: 0;" type="submit" value="Save" /> or <input id="ajax-cancel" class="btnCancel" style="margin-bottom: 0;" type="button" value="Cancel" /></div></form>';
	$(element).html(form_html);
}

function showSignin() {
    $("#popupBackground").show().centerInClient();
	if ($.browser.msie) {
		$('.iframe_wrapper').show();
		$('.iframe_wrapper').height($('#popupBackground').height()); 
	   	$('.iframe_wrapper').width($('#popupBackground').width());
	}
}

function deleteConfirm(delete_this) {
  if (!confirm("Are you sure you want to delete this " + delete_this + "?")) {
    return false;
  }
}

function showHelpArticle(art_id, ses_id) {
	$('.popupHeadline').hide();
	$('.popupMain').hide();
	
	$.ajax({
        url: '/article/help/' + art_id + '/',
        type: 'POST',
        dataType: 'xml',
        data: "uid="+ses_id,
        timeout: 5000,
        error: function(xhr, tstatus, error_thrown) {
        	alert('Error performing action.  Try again later. If the problem persists, contact support.');
        },
        success: function(xml) {
			var title = $(xml).find('article_name').text();
			var subtitle = $(xml).find('article_subname').text();
            var body = $(xml).find('article_body').text();
			if (subtitle) {
				title = title + ' - ' + subtitle;
			}
            $('#popupArticleTitle').html(title);
			$('#popupArticleBody').html(body+'<p><button class="button" onclick="$(\'#popupBackground\').hide(); return false;"><span>Close&nbsp;</span></button></p>');
			$('#articleHeadline').show();
			$('#popupArticleBody').show();
			$('#popupBackground').show().centerInClient();
			
			if ($.browser.msie) {
	    		$('.iframe_wrapper').show();
	    		$('.iframe_wrapper').height($('#popupBackground').height()); 
	    	   	$('.iframe_wrapper').width($('#popupBackground').width());
		   	}
			
        }
    });
}

function showSendFriend(item_type, item_id) {
	$('.popupHeadline').hide();
	$('.popupMain').hide();
	$('#sendFriendHeadline').show();
	$('#popupSendFriendBody').show();
	$('#popupBackground').show().centerInClient();
	$('#header_send_friend_item_type').val(item_type);
	$('#header_send_friend_item_id').val(item_id);
}

function sendFriendSubmit() {
	$('#header_sf_submit').hide();
	$('.spinner').show();
	$.ajax({
        url: '/user/send_friend/',
        type: 'POST',
        dataType: 'xml',
        data: $("#header_send_friend").serialize(),
        timeout: 5000,
        error: function(xhr, tstatus, error_thrown) {
            alert('Error performing action.  Try again later. If the problem persists, contact support.');
			$('#header_sf_submit').show();
			$('.spinner').hide();
        },
        success: function(xml) {
			var result = $(xml).find('result').text();
			if (result == 'success') {
				$('#popupRecommendForm').hide();
				$('#popupRecommendFormComplete').show();
			} else {
				var name_error = $(xml).find('name_error').text();
				var from_email_error = $(xml).find('from_email_error').text();
				var to_email_error = $(xml).find('to_email_error').text();
				$('.header_sf_error_text').html('&nbsp;');
				$('.header_sf_error_row').removeClass('row-error');
				if (name_error != '') {
					$('#header_sf_tr_name').addClass('row-error');
					$('#header_sf_error_name').html('<strong>'+name_error+'</strong>');
				}
				if (from_email_error != '') {
					$('#header_sf_tr_from_email').addClass('row-error');
					$('#header_sf_error_from_email').html('<strong>'+from_email_error+'</strong>');
				}
				if (to_email_error != '') {
					$('#header_sf_tr_to_email').addClass('row-error');
					$('#header_sf_error_to_email').html('<strong>'+to_email_error+'</strong>');
				}
			}
			$('#header_sf_submit').show();
			$('.spinner').hide();
        }
    });
}

function checkName() {
	var val = $('#main_user_uname').val();
	var unameRegex = /^[A-Za-z0-9][\-_A-Za-z0-9]{1,48}[A-Za-z0-9]$/;
	if (val == '' || !unameRegex.test(val)) {
		alert('You need to enter a valid screen name before we can check it for you! A valid username must start with a letter and end with a letter or number.');
		return;
	}
	$('.spinner').show();
	$.ajax({
        url: '/user/check_availability/',
        type: 'POST',
        dataType: 'xml',
		data: 'uname='+val,
		timeout: 5000,
        error: function(xhr, tstatus, error_thrown) {
            alert('Error performing action.  Try again later. If the problem persists, contact support.');
			$('#header_sf_submit').show();
			$('.spinner').hide();
        },
		success: function(xml) {
			var result = $(xml).find('result').text();
			if (result == 'available') {
				$('#main_uname_check').html('<span style="color: #082;">'+val+' is available.</span>');
				$('#main_uname_check_row').show();
			} else {
				$('#main_uname_check').html('<span style="color: #c00;">'+val+' is not available.</span>');
				$('#main_uname_check_row').show();
			}
			$('.spinner').hide();
		}
	});
}

function vipQuestion(qid, aid) {
	$('.spinner').show();
	var path = '/vip/answerxml/';
	if (qid && aid) {
		path += qid + '/' + aid + '/';
	}
	$.ajax({
        url: path,
        type: 'POST',
        dataType: 'xml',
		data: '',
		timeout: 5000,
		error: function(xhr, tstatus, error_thrown) {
            alert('Error performing action.  Try again later. If the problem persists, contact support.');
			$('.spinner').hide();
        },
		success: function(xml) {
			$('.spinner').hide();
			var result = $(xml).find('result').text();
			if (result == 'error') {
				alert('Error performing action.  Try again later. If the problem persists, contact support.');
				return;
			}
			var vipq_id = $(xml).find('vipq_id').text();
			var html = '';
			// Test is finished.  Write out the html for getting the results.
			if (vipq_id == '0') {
				html = '<a href="/vip/results/"><img src="/i/vip_results.jpg" width="660" height="244" border="0"/></a>';
			} else {
				var vipq_answers = $(xml).find('vipq_answers').text();
				var vipq_question = $(xml).find('vipq_question').text();
				var vipq_question_image = $(xml).find('vipq_question_image').text();
				var vipq_a1_image = $(xml).find('vipq_a1_image').text();
				var vipq_fixed_order = $(xml).find('vipq_fixed_order').text();
				var vipq_answer;
				var vipq_answer_image;
				var answer_values = new Array(vipq_answers);
				for (var i = 1; i <= vipq_answers; i++) {
					answer_values[(i - 1)] = i;
				}
				if (vipq_fixed_order != 1) {
					answer_values.sort(function() {return 0.5 - Math.random()});
				}
				// Build the html for the new question.
				html += '<img class="spinner" src="/i/spinner.gif" width="16" height="16" alt="" />';
				html += (vipq_a1_image) ? '<div id="vipQi">' : '<div id="vipQ">';
				html += '<h2>' + vipq_question + '</h2>';
				if (vipq_question_image) {
					html += '<div class="vipPhoto"><img src="http://' + vipq_question_image + '" width="130" height="130" border="0" alt=""></div><ul class="answers2">';
				} else {
					html += '<ul class="answers">';
				}
				
				for (i = 0; i < vipq_answers; i++) {
					html += '<li><a href="#" onclick="vipQuestion(' + vipq_id + ', ' + answer_values[i] + '); return false;">';
					vipq_answer = $(xml).find('vipq_a'+answer_values[i]).text();
					vipq_answer_image = $(xml).find('vipq_a'+answer_values[i]+'_image').text();
					if (vipq_answer_image) {
						html += '<img src="http://' + vipq_answer_image + '" width="130" height="130" border="0" alt="" /></a>';
						if (vipq_answer) {
							html += '<p>' + vipq_answer + '</p>';
						}
					} else {
						html += vipq_answer + '</a>';
					}
					html += '</li>';
				}
				html += '</ul></div>';
			}
			$('#findhiVipBody').html(html);
			
		}
	});
}

// Modified from http://clownsinmycoffee.net/2008/04/18/add-shift-select-with-jquery/
jQuery.fn.shiftSelect = function(all_handle) {
    var checkboxes = this;
    var lastSelected;
	var thisHandle = this.attr('class');
    jQuery(this).click( function(event) {
        if ( !lastSelected ) {
            lastSelected = this;
            return;
        }
        if ( event.shiftKey ) {
            var selIndex = checkboxes.index(this);
            var lastIndex = checkboxes.index(lastSelected);
            var checkValue = lastSelected.checked;
            if ( selIndex == lastIndex ) {
                return true;
            }

            var end = Math.max(selIndex,lastIndex);
            var start = Math.min(selIndex,lastIndex);
            for (i=start;i<=end;i++) {
                checkboxes[i].checked = checkValue;
            }
        }
        lastSelected = this;

		if (all_handle && $("."+thisHandle+":checkbox:checked").length == $("."+thisHandle+":checkbox").length) {
            $(all_handle).attr('checked', true);
        }
    });
}

