/**
 *  List & paging funcs
 */
function prepPager()
{
	$("#tabView").html("<center><img src='"+base_dir+"img/load.gif' /></center>")
}

function pageShouts(type,json,offset)
{
	$('#os_'+type).empty()
	if(json.shouts == null) $('#os_'+type).append('<h4 align="center" class="pinktext">We couldn\'t find results for <b class="whitetext">\''+json.notfound+'\'</b></h4>')
	else
	{
		for(i in json.shouts){
			var shout = json.shouts[i];
			if(shout.title.length > 34)
				var shout_title = shout.title.substr(0, 34)+"...";
			else
				var shout_title = shout.title;
			
			var row = "<table><tr><td class='avatar'>"
				if(shout.user_id == null)
					row += "<img src='"+base_dir+"users/avatar/user_id/"+shout.user_id+"' alt='avatar' /></td>"
				else
				{
					row += "<a href='"+base_dir+"users/profile/user_id/"+shout.user_id+"'>"
				
					if(shout.user_id.indexOf(':') != -1)
					{
						var info = shout.user_id.split(':')
						row += "<img src='"+base_dir+"extUsers/avatar/network/"+info[0]+"/user_id/"+info[1]+"' alt='avatar' /></a></td>"
					}
					else row += "<img src='"+base_dir+"users/avatar/user_id/"+shout.user_id+"' alt='avatar' /></a></td>"
				}
				
				row += "<td class='title'><div class='outshoutname'><a href='"+base_dir+"outshouts/receive/outshout_id/"
						+ shout.outshout_id +"' class='title'>"+shout_title+"</a><br/>"
						+ "<span style='color:#CC6633'>"+shout.sender+"</span>"
						
				if(shout.user_id != null && shout.user_id.indexOf(':') == -1)
					row += " <a href='"+base_dir+"users/profile/user_id/"+shout.user_id+"' style='font-size:8pt;font-weight:700'>(profile)</a>"
				
				row +=	"</div></td><td class='added'>Added: <em>"+shout.created+"</em></td>"
						+"<td><em><span class='white'>Listens:</span> "+shout.views+"<br/><span class='white'>Comments:</span> "+shout.comment_count+"</em></td>"
						+"<td class='last'><a href='"+base_dir+"outshouts/receive/outshout_id/"+shout.outshout_id+"' title='Play'>"
						+"<img src='"+base_dir+"img/buttons/browse_play.gif' alt='Play' /></a></td></tr></table>"
					
			$('#os_'+type).append(row);
		}

		var method = 'get'+type.substr(0,1).toUpperCase()+type.substr(1,type.length)
		var node = 'page_os_'+type
		setPageLinks(json,offset,method,node)
	}
}

function setPageLinks(json,offset,method,node)
{
	var pages = ''
	if (json.count <= json.limit)  // there's only a single page, so clear paging & return
	{
		$('#'+node).empty()
		return
	}
	
	var rangeCount = json.limit * 8
	var range = 0
	for(x = 0; x <= json.offset;x += rangeCount)
		range = x / rangeCount
	
	 if(range > 0) pages += "<li><a href='#' onclick='return "+method+"("+ ((range*rangeCount)-json.limit) +")'>. . .</a></li>"
	
	for(x = (range*rangeCount);x <  ((range+1)*rangeCount) && x < json.count;x += json.limit)
	{
		if(x == offset) pages += "<li class='selected'>"
		else pages += "<li>"
		
		pages += "<a href='#' onclick='return "+method+"("+(x)+")'>"+((x/json.limit)+1)+"</a></li>"
	}
	
	if (((range+1)*rangeCount) < json.count)
		pages += "<li><a href='#' onclick='return "+method+"("+x+")'>. . .</a></li>"
		
	nextOffset = offset + json.limit;
	if (json.count > 0 && nextOffset < json.count) pages += "<li><a href='#' onclick='return " + method + "(" + nextOffset +"); return false;'>next</a></li>";
	$('#'+node).html(pages)
}

function smartyPager(method)
{
	// numeric paging buttons
	var prev=0;limit=0
	$("#paging>li>a:not(#next)").each(function(){num=parseInt($(this).attr('id').replace(/page_/,''));limit=num-prev;prev=num;
									$(this).click(function(){eval(method)($(this).attr('id').replace(/page_/,''))})})

	// next button
	if($("#paging>li.selected>a").length > 0)
	{
		var offset = parseInt($("#paging>li.selected>a").attr('id').replace(/page_/,''))
		$('#paging>li>a#next').click(function(){eval(method)(limit+offset)})
	}
}

/**
 * Login-related functions
 */
function login(pars)
{
	// remove any previous error
	//$("#loginError").html()
	
	// set remember flag
	if($('#remember:checked').val()) var remember = 1
	else var remember = 0

	var pars = 'login='+ escape($('#login_email').val())+'&password='+escape($('#password').val())+'&remember='+remember+'&json=1';
	
	$.ajax({type:'POST',url:base_dir+'users/login',data: pars, dataType:'json',
		success:function(json){if(json.error) $("#loginError").html(json.error);else window.location.reload();}});
		return false;
}

// for header refresh from Flex login
function flexLogin()
{
	$('#header').load(base_dir+'home/navFlex')
}

// for header refresh from Flex login to ext network
function flexLoginExt()
{
	$('#header').load(base_dir+'home/navExt')
}

function loginPopup()
{
	var flexApp = getFlexApp('flexContainer')
	flexApp.login()
	flexApp.focus()
	return false
}

function regSelector()
{
	if(flex) regPopup()
	else regPopupHtml()
}

function regPopup()
{
	var flexApp = getFlexApp('flexContainer')
	flexApp.createAccount()
	flexApp.focus()
	return false
}

function loginPopupHtml()
{
	$('#box_join').hide()
	$('#box_forgot').hide()
	$('#box_login').show()
	$('#login_float').jqm().jqmShow()
}

function regPopupHtml()
{
	$('#box_login').hide()
	$('#box_forgot').hide()
	$('#box_join').show()
	$('#login_float').jqm().jqmShow()
}
function mobilePopupHtml()
{
	$('#login_float').hide()
	$('#box_mobile').show()
	$('#mobile_float').jqm().jqmShow()
}
function loginClose()
{
	$('.login_float').jqm().jqmHide();
}
function forgotPw()
{
	$.ajax({type:'POST',url:base_dir+'users/forgot',data: 'identifier='+escape($('#identifier').val())+'&json=1', dataType:'json',
		success:function(json){if(json.error) makePopUp("", json.error)
		else $('#form_container').html("<div class='login_inner'><p class='label_p'><br /><br />Please click the link in the email we sent you to reset your password.</p></div>")}});
		return false
}
/**
 * Flex funcs
 */
function getFlexApp(appName)
{
	if(navigator.appName.indexOf("Microsoft") !=-1)
    	return window[appName]
    else
    	return document[appName]
}


function loadMainSWF()
{
	loadSWF(mainSWF,"flexContainer",flashVars,830,550)
	if(mainSWF.indexOf('initialView') != -1) // if this is initial view, mark as loaded
		$.get(base_dir+"home/setFlexLoaded")
}

function loadSWF(swf,id,flashvars,width,height)
{
	if(swfobject.hasFlashPlayerVersion(flash_version))
	{
		var params = {quality:"high",allowScriptAccess:"always",wmode:"transparent"}
		swfobject.embedSWF(base_dir+"flash/"+swf, id, width, height, flash_version,'',flashvars,params,false)
	}
	else
	{
		makePopUp('Whoops!','You need a higher version of Flash to use our site.<p/>'
			+ 'Please click <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">here</a>'
			+ ' to get a newer version from the Adobe website.')
	}
}

/**
 * Utility funcs
 */
function selTab(tab)
{
	$('ul.tabs>li.selected').removeClass()
	$('#'+tab).parent().addClass("selected")
	$('#tabView').empty()
	return false;
}

function makePopUp(a, b) {
	$('#errortitle').html(a);
	$('#errormessage').html(b);
	$('#errorbox').jqmShow();
}

function chkPhoneNumber(phone)
{
	var re = /^(?:1\D?)?\D*([2-9][0-8]\d)\D*([2-9]\d{2})\D*(\d{4})\D*$/
	var matches = phone.match(re)
	if(matches != null)
	{
		phone = matches[1]+"-"+matches[2]+"-"+matches[3]
		return phone
	}
	else
		return false
}

function checkForCookies()       
{           
	document.cookie = "cookieTest=testing"
	if(document.cookie.match('(^|;) ?cookieTest=([^;]*)(;|$)') != null)
		document.cookie = "cookieTest=testing; expires=01/01/2000 00:00:00"
	else
		makePopUp("Whoops!","<span style='font-weight:900;color:#FFCC99'>Cookies</span> are required<br/>to use this site." +
						"<P>Please enable cookies in your browser before proceding.")	  
} 

/**
 * Find Mobile OS
 */
function getMobileOS()
{
	var phone = $('#mobile').val()
	phone = chkPhoneNumber(phone)
	if(!phone)
	{
		$('.error_p').html('The number entered does not appear to be valid. Please be sure to include the area code.')
		return false
	}
	else
	{
		$.getJSON(base_dir+'outshouts/getForPhone/phone/'+phone+'/json',
			function(json){if(json.error){$('.error_p').html(json.error)}
				else window.location = base_dir+'outshouts/receive/outshout_id/'+json.outshout_id+'/code/'+json.code})
		return false
	}
}

/**
 * Old Nav functions
 */
function togglevis(s) {
	if (document.getElementById(s).style.display != '') { 
				document.getElementById(s).style.display = ''; 
	} else { 
		document.getElementById(s).style.display = 'none'; 
	}
}

// Help/Hints
function toggleHelp(obj,id,isButton) {
	var target = document.getElementById(id);
	
	if (target.style.display == "none") {
		if (isButton) {
			target.style.left = getLeft(obj) + obj.offsetWidth + 5 + "px";
			target.style.top = getTop(obj) + "px";
		} else {
			target.style.left = getLeft(obj) + 30 + "px";
			target.style.top = getTop(obj) - 7 + "px";
		}
		target.style.display = "";
	} else {
		target.style.display = "none";
	}
}

function getTop(div) {
	yPos = div.offsetTop;
	tempEl = div.offsetParent;
	while (tempEl != null) {
		yPos += tempEl.offsetTop;
		tempEl = tempEl.offsetParent;
	}	
	
	return yPos;
}

function getLeft(div) {
	xPos = div.offsetLeft;
	tempEl = div.offsetParent;
	while (tempEl != null) {
		xPos += tempEl.offsetLeft;
		tempEl = tempEl.offsetParent;
	}
	
	return xPos;
}

  if(window.attachEvent)
    window.attachEvent("onload",setListeners);

  function setListeners(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++){
      inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
    }
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++){
      selectList[i].attachEvent("onpropertychange",restoreStyles);
      selectList[i].style.backgroundColor = "";
    }
  }

  function restoreStyles(){
    if(event.srcElement.style.backgroundColor != "")
      event.srcElement.style.backgroundColor = "";
  }
  
function shareOnFacebook(url){
	if(url == null) url = location.href
	t=document.title
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false
}

function shareOnTwitter(url){
	if(url == null) url = location.href
	window.open('http://twitter.com/home?status=Check+this+out:+'+encodeURIComponent(url),'sharer','');
	return false
}

function openTwitter()
{
	window.open('http://twitter.com/outshouts','','toolbar=0,status=0,scrollbars=1,width=800,height=600');
}
