// Topics global matches descriptive text with their category ids
var topics = [];
topics['astrology']='1120';

var CURRENTPAGE = '';
var CURRENTTOPIC ='';
var EXPERTSPERPAGE = 3;
var KBID = '1970';

// 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 = 'http://www.liveperson.com/Registration/OfflineRegistration/SendRequest.aspx';
        if(expertStatus == 1 || expertStatus == 4)
        {
        contactLink = 'http://www.liveperson.com/session/session-selector.aspx';
        }		
	
		
		//start the expert profile
		var expertString = "<div id=\"mygrid_Expert_"+i+"\">"+
"<div class=\"grid\">"+
"<div class=\"top_section\">"+
"<div class=\"profile_photo\">"+
"<a href=\"http://www.liveperson.com/Professional/expert-profile.aspx?kbid="+KBID+"&CatID="+catID+"&ExpID="+expertID+"&FM=yes \"><img class='photo' src='"+expertThumbnail+"' title='"+expertName+"' alt='"+expertName+"' /></a>"+
"</div>"+
"<div class=\"right_banner\"><img src=\"http://liveperson-consumer-marketing.s3.amazonaws.com/small_profiles/160x196_right_banner_blue.png\" />"+
"</div>"+
"</div>"+
"<div class=\"middle_section\">"+
"<h2><a id='profile_url' href=\"http://www.liveperson.com/Professional/expert-profile.aspx?kbid="+KBID+"&CatID="+catID+"&ExpID="+expertID+"&FM=yes \" class='expname'>"+expertName+"</a></h2>"+
"<p class='description'>"+expertDetailedDescription+"</p>"+
"</div>"+
"<div class=\"bottom_section\">"+
"<a href=\""+contactLink+"?kbid="+KBID+"&ExpID="+expertID+"&catID="+catID+"&FM=yes\" title='Contact Live' class='contact-link' >"+expertStatus+"</a>"+
"<div class=\"right_side\">"+
"<span class='rating'><img src='http://liveperson-partners.s3.amazonaws.com/shared/graphics/rate"+expertAverageRating+".png' width='48' /></span>"+
"<span class='reviews'><a href=\"javascript:OpenWindow('http://www.liveperson.com/rating/expert-rating.aspx?i_MemID="+expertID+"','450','700')\">"+expertReviewsCount+" reviews</a></span>"+
"<span class='perminute'>$ "+expertFee+"/min</span>"+
"</div>"+
"</div>"+
"</div>"+
"</div>";

		$("#astrology").append(expertString);	
	}

	// set pagination
	writePagination(totalpages, CURRENTPAGE, CURRENTTOPIC);
	
	// clean up profile descriptions
	loop('mygrid', set_status, ['Chat Live','']); 
    loop('mygrid', remove_tags, []); 
	loop('mygrid', trim_description, 40 ); 
	//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 = '1120'; } //this id is the spirituality 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'
	});			
	

	

}

//default to general counseling category
$(document).ready(function () {
	//onload read topic / cateogry from url variable s'topic' 
	URLvars = getUrlVars();
	var category = 'astrology'; //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	
	
	
})