// Topics global matches descriptive text with their category ids
var topics = [];
topics['counseling']='10341';
topics['parenting']='10349';
topics['depression']='10367';
topics['love']='10342';
topics['anxiety']='10364';
topics['marriage']='10348';
topics['sex']='10344';

var CURRENTPAGE = '';
var CURRENTTOPIC ='';
var EXPERTSPERPAGE = 6;


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function OpenWindow(url, width, height)
{
    if (typeof (width) == "undefined")
    {
        width = 420;
    }
    if (typeof (height) == "undefined")
    {
        height = 300;
    }
    window.open(url, 'winHelp', "width=" + width + ", height=" + height + ", resizable=1, scrollbars=1");
}

//writes the pagination and the title in the pagination bar
function writePagination(totalpages, currentpage, topic){

	//create and validate ends
	var pastpage = parseInt(currentpage) - 1;
	var nextpage = parseInt(currentpage) + 1;
	if(pastpage < 1){pastpage = 1;}
	if(nextpage > totalpages){nextpage = totalpages;}
	//wrapper styles
	var wrapperstart = '<li class="pagination">'
	var wrapperend = "</li>";
	
	var backarrow =	wrapperstart + '<a href="?topic='+topic+'&page='+pastpage+'"> < previous </a>' + wrapperend;
	var forwardarrow = wrapperstart + '<a href="?topic='+topic+'&page='+nextpage+'"> next > </a>' + wrapperend;
	var pagestext = wrapperstart+ 'Page ' + currentpage + ' of '+totalpages + wrapperend;
	
	// write out links for each page
	//for(var i=1; i<=totalpages; i++){
	//	if(i == currentpage)
	//	{		pagestext = pagestext + wrapperstart + i.toString() + wrapperend;}
	//	else
	//	{		pagestext = pagestext + wrapperstart + ' <a href="?topic='+topic+'&page='+i.toString()+'">'+i.toString()+'</a> '+wrapperend;}
	//	}

	//title text is updated for each topic/category
	var titleformat = '<li class="pagination"> TITLETOPICTEXT Counselors </li>';
	var titletext = 'Professional'; //default
	if(CURRENTTOPIC != 'counseling'){ titletext=$('#'+CURRENTTOPIC+'link').text() }
	var finaltext = titleformat.replace('TITLETOPICTEXT', titletext);
	
	$('.gridheader').empty();
	$('#gridtitle').append(finaltext);
	$('#pagination').append(backarrow + ' ' + pagestext +' '+forwardarrow);
}

//obj is returned json data
function api_expertProfiles(obj){
	var totalpages = Math.ceil( obj.total / EXPERTSPERPAGE );
	// cycle through experts and create their html
	for(var i=0;i<obj.experts.length;i++){
	
		var catID = obj.category.id;
		var expertID = obj.experts[i].id;
		var expertThumbnail = obj.experts[i].thumbnail;
		var expertName = obj.experts[i].name;
		var expertAverageRating = Math.round(obj.experts[i].averageRating);
		var expertReviews = obj.experts[i].reviews;
		var expertReviewsCount = obj.experts[i].reviewsCount;
		var expertFee = obj.experts[i].fee;
		var expertDetailedDescription = obj.experts[i].description;
		var expertContactLive = obj.experts[i].contactLive;
		var expertStatus = obj.experts[i].status;
		var expertContactOffline = obj.experts[i].contactOffline;
		
		var contactLink = expertContactOffline;
		if(expertStatus == 1 || expertStatus == 4)
		{
		contactLink = expertContactLive;
		}
		
	
		
		//start the expert profile
		var expertString = "<div id='mygrid_Expert_"+i+"'>"+
		"<div class='grid'>"+
		"<div class='profile-info'>"+
		"<div class='profile-photo'><a href=\"javascript:OpenWindow('http://www.liveperson.com/Professional/expert-profile.aspx?CatID="+catID+"&ExpID="+expertID+"','970','800') \"><img class='photo' src='"+expertThumbnail+"' title='"+expertName+"' alt='"+expertName+"' /></a></div>"+
		"<span class='rating'><img src='http://liveperson-partners.s3.amazonaws.com/shared/graphics/rate"+expertAverageRating+".png' /></span>"+
		"<cite class='reviews'><a href=\"javascript:OpenWindow('http://www.liveperson.com/rating/expert-rating.aspx?i_MemID="+expertID+"','450','700')\">"+expertReviewsCount+" reviews</a></cite>"+
		"<cite class='perminute'>$ "+expertFee+"/min</cite>"+
		"</div>"+
	"<div class='profile-desc'>"+
		"<h2><a id='profile_url' href=\"javascript:OpenWindow('http://www.liveperson.com/Professional/expert-profile.aspx?CatID="+catID+"&ExpID="+expertID+"','970','800')\" class='expname'>"+expertName+"</a></h2>"+
		"<p class='description'>"+expertDetailedDescription+"</p>"+
		"<a href=\"javascript:OpenWindow('"+contactLink+"','680','700')\" title='Contact Live' class='contact-link' >"+expertStatus+"</a>"+
		"</div>"+
"</div>"+
"</div>";

		$("#expertgrid").append(expertString);	
	}

	// set pagination
	writePagination(totalpages, CURRENTPAGE, CURRENTTOPIC);
	
	// clean up profile descriptions
	loop('mygrid', set_status, []); 
    loop('mygrid', remove_tags, []); 
	loop('mygrid', trim_description, 145 ); 
	//remove target blank that is inserted from the trim_description function above
	$('a').attr('target','');
}

//updates the experts displayed to the given category
function changeTo(category){
	var catID = topics[category];
	var offset = ((CURRENTPAGE-1) * EXPERTSPERPAGE) + 1; //offset for retreving experts
	if(undefined == catID){ catid = '10341'; } //this id is the general counseling id, used as a backup
	$("#expertgrid").empty();

	//build GET url and fetch the results
	var url = 'http://apis.liveperson.com/experts.svc/1.1/categories/'+catID+'/jsonp?count='+EXPERTSPERPAGE+'&index='+offset+'&sort=9&callback=api_expertProfiles'
	$.ajax({
		type:'GET',
		url: url,
		dataType: 'script'
	});			
	
	//highlight the menuitem with the current category:
	$('#'+category+'link').css('font-size','16px');
	

}


//default to general counseling category
$(document).ready(function () {
	//onload read topic / cateogry from url variable s'topic' 
	URLvars = getUrlVars();
	var category = 'counseling'; //default
	if(undefined != topics[URLvars['topic']]) 
	{ category=URLvars['topic']; }

	//read page # from url variable 'page'
	var page = 1;
	if(URLvars.length>0 && undefined!= URLvars['page'] && URLvars['page'].match(/^\d+$/))
	{ page  = URLvars['page'] }
	
	//set global page and categories
	CURRENTPAGE = page;
	CURRENTTOPIC = category;
	
	//update display of experts to the given category and page
	changeTo(category) //change to specified topic	
	
	
$("#depressionlink").attr({href: "?topic=depression&page=1"});
$("#parentinglink").attr({href: "?topic=parenting&page=1"});
$("#lovelink").attr({href: "?topic=love&page=1"});
$("#anxietylink").attr({href: "?topic=anxiety&page=1"});
$("#marriagelink").attr({href: "?topic=marriage&page=1"});
$("#sexlink").attr({href: "?topic=sex&page=1"});

var x = window.location.href
if(x.split('?')[0].charAt(x.split('?')[0].length-1) != '/') { window.location.replace(x+'/');}

})
