var ie6;
if($.browser.msie && $.browser.version=="6.0"){
	ie6 = true;
}

var lawyerIndexArray = new Array();
var Lawyers = {};

function carousel_itemLoadCallback(carousel, state)
{
    $(".lawyer_thumb", "#carousel_thumbs").live("click", function(e){
        carousel.scroll(parseInt(this.rel));
		return false;
	});

	$(".lawyer_thumb", "#name_panel").live("click", function(e){
		carousel.scroll(parseInt(this.rel));
		return false;
	});

    var showFind = state == 'init' && document.location.hash == "#Find_By_Name";
    if( showFind )
    {
        toggleSearch('show');
        $('.loading').removeClass('.loading');
        return;
    }

	// initialize the q and a section
    initQandA(carousel.currentIndex());

    // Only load items if they don't already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }

    $.get(
        '/feeds/lawyer_carousel/' + carousel.currentIndex() + '/',
        {},
        function(data) {
            carousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
        },
        'json'
    );
};


function carousel_itemAddCallback(carousel, first, last, data)
{
	idx = carousel.currentIndex();
    var item = carousel.add(idx, buildStatCard(data));

    if(!ie6){
        $(".bio_card", item).fadeIn("def", function(){ });
    } else {
        $(".bio_card", item).show();
    }

    if(!ie6){
        $("a[title]", item).qtip({
            style: {
                name: 'kestyle',
                tip: true
            },
            position: {
                corner: {
                    target: 'topMiddle',
                    tooltip: 'bottomMiddle'
                }
            }
        });
    }
    if(firstload){
        firstload = false;
        loadBioModules(carousel);
    }
};


function hideAllModules(carousel, current, b, c, d){
	//alert("hideAllModules");
	//alert(carousel + ", " + current + ", " + b + ", " + c + ", " + d);

	// Make sure Search Panel is hidden:
	toggleSearch("hide");
	
	$(current).addClass("selected");
	$(".module .content", "#module_containers").hide();
	$(".module", "#module_containers").addClass("loading");
}


function loadBioModules(carousel, last, lastNum, c, d) {
	if(firstload){return;}

	$("#lawyer_thumb_" + lastNum, "#carousel_thumbs").removeClass("selected");
	$("#lawyer_thumb_" + carousel.currentIndex(), "#carousel_thumbs").addClass("selected");
	//var hash = $("#lawyer_thumb_" + carousel.currentIndex(), "#carousel_thumbs").attr("href");
    var hash = $('#lawyer_thumb_' + carousel.currentIndex()).attr('href');
	
	if(!ie6){
		hash = hash.replace(/^.*#/, '');
		$.historyLoad(hash);
    }
    
    $(last).removeClass("selected");

    
	// The url for lawyer data requires the lawyers ID, which maps to carousel id
	$.get(
		'/feeds/lawyer_story/' + carousel.currentIndex() + '/',
		{},
		function(data) {
			var theStory = carousel_decodeEntities(data);
			pullStory(theStory);
		},
		'json'
	);
}

function LawyerStat(field,text)
{
    this.Field = field;
    this.Text = text;
}

function getRandom(max)
{
    return Math.floor(Math.random() * max+1)-1;
}

// Stat Card Base HTML Template
function buildStatCard(json) {
    var html = "<div class='bio_card'>";
    html += "<div class='column_1'><img src='/site_media/";
    html += carousel_decodeEntities(json[0].fields['photo']);
    html += "'><\/div><div class='column_2'><h1>";
    html += carousel_decodeEntities(json[0].fields['name']);
    html += "<\/h1><div class='contact_info'><span class='info_title'>";
    html += carousel_decodeEntities(json[0].fields['title']);
    html += "<\/span><span class='info_email'>";
    html += carousel_decodeEntities(json[0].fields['email']);
    html += "<\/span><span class='info_number'>";
    html += carousel_decodeEntities(json[0].fields['phone']);
    html += "<\/span></div><p class='brief'>";

    html += carousel_decodeEntities(json[0].fields['brief']);
    html += "<\/p><ul>";


    // Start pulling random stats here

    var options = Array
    (
        new LawyerStat('music','On My iPod')
        , new LawyerStat('character','Sitcom Character')
        , new LawyerStat('site', 'Site I Frequent')
        //, new LawyerStat('tv_character', 'TV Character')
        , new LawyerStat('law_movie', 'Legal Show')
        , new LawyerStat('vacation', 'Perfect Vacation')
        , new LawyerStat('sports', 'Favorite Sport(s)')
        , new LawyerStat('game', 'Favorite Game')
        , new LawyerStat('animal', 'Favorite Animal')
        , new LawyerStat('quote', 'Favorite Quote')
    );
    var start = getRandom(options.length);
    var index = start;
    for( var i = 0; i < 4; i++, index++) // this would be much better using recursion, but i'm lazy right now
    {
        if( index >= options.length ) // if we go outside the bounds then just reset to the first element
            index = 0;

        var stat = options[index];
        var value = carousel_decodeEntities(json[0].fields[stat.Field]);
	var text = stat.Text;
        var inc = 0;
        while( value == '' && inc < options.length) // keep looping if we have no value, or if we've checked everything
        {
            index++; inc++;
            if( index >= options.length ) // if we go outside the bounds then just reset to the first element
                index = 0;
            value = carousel_decodeEntities(json[0].fields[options[index].Field]);
	    text = options[index].Text;
        }

        if( value == '' ) // if we still have nothing, then exit
            continue;

        html += "<li><span class='title'>" + text + ":<\/span><span class='value'>";
        html += value;
        html += "<\/span><\/li>"
    }

//    html += "<ul><li><span class='title'>On My iPod:<\/span><span class='value'>";
//    html += carousel_decodeEntities(json[0].fields['music']);
//    html += "<\/span><\/li><li><span class='title'>TV Character:<\/span><span class='value'>";
//    html += carousel_decodeEntities(json[0].fields['character']);
//    html += "<\/span><\/li><li><span class='title'>Site I Frequent:<\/span><span class='value'>";
//    html += carousel_decodeEntities(json[0].fields['site']);
//    html += "<\/span><\/li><li><span class='title'>Pre-Court Ritual:<\/span><span class='value'>";
//    html += carousel_decodeEntities(json[0].fields['ritual']);
    html += "<\/ul><\/div>";

    // end random stats

    html += "<div class='card_foot'>";
    html += "<div class='mobile_tool'>";
    html += writePhone(carousel_decodeEntities(json[0].fields['mobile_tool']));
    html += "<\/div><div class='coffee'>";
    html += writeCoffeeCups(carousel_decodeEntities(json[0].fields['coffee']));
	html += "<\/div><div class='location'>";
	html += writeLocation(carousel_decodeEntities(json[0].fields['location']));
	html += "<\/div><div class='rockpaper'>";
	html += rockPaperScissor(json[0].fields['rock_papper_scissors']);
	html += "<\/div><\/div>";
	// html += "<\/div><div class='cases_won'>";
    // html += writeNumericImage(carousel_decodeEntities(json[0].fields['cases_won']));

    return html;
}


// Mobile Tool HTML Template
function writePhone(phone){
	var phoneHTML = "<h4><span>Mobile Tool:<\/span><\/h4>";
	var phoneStr = phone.toString();
	var phonesArry = phoneStr.split(",");
	
	for(var i=0; i< phonesArry.length; i++){
		switch(phonesArry[i]){
			case "Android":
				phoneHTML += "<a href='http://en.wikipedia.org/wiki/Android_(operating_system)' class='phone_android' target='_blank' title='" + phonesArry[i] + "'><span>" + phonesArry[i] + "<\/span><\/a>";
				break;
			case "Blackberry":
				phoneHTML += "<a href='http://en.wikipedia.org/wiki/BlackBerry' class='phone_blackberry' target='_blank' title='" + phonesArry[i] + "'><span>" + phonesArry[i] + "<\/span><\/a>";
				break;
			case "iPhone":
				phoneHTML += "<a href='http://en.wikipedia.org/wiki/IPhone' class='phone_iphone' target='_blank' title='" + phonesArry[i] + "'><span>" + phonesArry[i] + "<\/span><\/a>";
				break;
			case "PalmPre":
				phoneHTML += "<a href='http://en.wikipedia.org/wiki/Palm_Pre' class='phone_palmpre' target='_blank' title='" + phonesArry[i] + "'><span>" + phonesArry[i] + "<\/span><\/a>";
				break;
			case "PalmPro":
				phoneHTML += "<a href='http://en.wikipedia.org/wiki/Palm_Treo_Pro' class='phone_palmpro' target='_blank' title='" + phonesArry[i] + "'><span>" + phonesArry[i] + "<\/span><\/a>";
				break;
			default:
				phoneHTML += "<a href='http://en.wikipedia.org/wiki/Off-the-grid' class='phone_none' target='_blank' title='" + phonesArry[i] + "'><span>None<\/span><\/a>";
		}
	}
	return phoneHTML;
}

// Coffee Cups HTML Template
function writeCoffeeCups(num){
    var coffeeHTML = "<h4><span>Daily Cups of Coffee:<\/span><\/h4>";
    var wholeNum = Math.floor(num);
    var halfNum = null;
    if(num%1 > 0){ halfNum = true; }
    for(var i=1; i<=wholeNum; i++){ coffeeHTML += "<div class='coffee_full'><span>" + i + "<\/span><\/div>"; }
    if(halfNum){ coffeeHTML += "<div class='coffee_half'><span>" + .5 + "<\/span><\/div>"; }
    if(num == 0){ coffeeHTML += "<div class='coffee_none'><span>" + 0 + "<\/span><\/div>"; }
    return coffeeHTML;
}

function writeLocation(loc){
    var locHTML = "<h4><span>Location:<\/span><\/h4>";
    var locStr = loc.toString();
    switch(locStr){
    	case "New York":
    		locHTML += "<a href='http://en.wikipedia.org/wiki/New_York' class='location_newyork' target='_blank' title='" + locStr + "'><span>" + locStr + " Office<\/span><\/a>";
    		break;
   		case "Chicago":
   			locHTML += "<a href='http://en.wikipedia.org/wiki/Chicago' class='location_chicago' target='_blank' title='" + locStr + "'><span>" + locStr + " Office<\/span><\/a>";
    		break;
   		case "Florida":
   			locHTML += "<a href='http://en.wikipedia.org/wiki/Florida' class='location_florida' target='_blank' title='" + locStr + "'><span>" + locStr + " Office<\/span><\/a>";
    		break;
   		case "Los Angeles":
   			locHTML += "<a href='http://en.wikipedia.org/wiki/Los_Angeles' class='location_losangeles' target='_blank' title='" + locStr + "'><span>" + locStr + " Office<\/span><\/a>";
    		break;
    	case "Denver":
            locHTML += "<a href='http://en.wikipedia.org/wiki/Denver' class='location_denver' target='_blank' title='" + locStr + "'><span>" + locStr + " Office<\/span><\/a>";
        break;
        default:
	    	locHTML += "<a href='http://en.wikipedia.org/wiki/Lost_%28TV_series%29' class='location_other' target='_blank' title='" + locStr + "'><span>" + locStr + " Office<\/span><\/a>";
    		break;
    }
    return locHTML;
}



function rockPaperScissor(answer){
	
    var answerHTML = "<h4><span>Rock, Paper, Scissor:<\/span><\/h4>";
    var answerStr = ( answer == null ) ? "Scissor" : answer.toString();
    switch(answerStr){
    	case "Rock":
    		answerHTML += "<a href='javascript:return false;' class='rps_rock' title='" + answerStr + "'><span>" + answerStr + "<\/span><\/a>";
    		break;
   		case "Paper":
   			answerHTML += "<a href='javascript:return false;' class='rps_paper' title='" + answerStr + "'><span>" + answerStr + "<\/span><\/a>";
    		break;
    	case "Scissor":
	    	answerHTML += "<a href='javascript:return false;' class='rps_scissor' title='" + answerStr + "'><span>" + answerStr + "<\/span><\/a>";
    		break;
    	default:
	    	answerHTML += "<a href='javascript:return false;' class='rps_scissor' title='" + answerStr + "'><span>" + answerStr + "<\/span><\/a>";
    		break;
    }
    return answerHTML;
}



function writeworkBest(time){
    var timeHTML = "<h4><span>I work best during:<\/span><\/h4>";
    var timeStr = time.toString();
    switch(timeStr){
    	case "Night":
    		timeHTML += "<a href='http://en.wikipedia.org/wiki/Night_owl_(person)' class='time_night' target='_blank' title='The " + timeStr + "'><span>The " + timeStr + "<\/span><\/a>";
    		break;
   		case "Day":
   			timeHTML += "<a href='http://en.wikipedia.org/wiki/Lark_%28person%29' class='time_day' target='_blank' title='The " + timeStr + "'><span>The " + timeStr + "<\/span><\/a>";
    		break;
    	case "All Day":
	    	timeHTML += "<a href='http://en.wikipedia.org/wiki/Insomnia' class='time_all' target='_blank' title='" + timeStr + "'><span>" + timeStr + "<\/span><\/a>";
    		break;
    	default:
	    	timeHTML += "<a href='http://en.wikipedia.org/wiki/Insomnia' class='time_all' target='_blank' title='" + timeStr + "'><span>" + timeStr + "<\/span><\/a>";
    		break;
    }
    return timeHTML;
}


// Numeric Image HTML Template - (Deprecated)
function writeNumericImage(num){
    var numHTML = "<h4><span>Total Cases:<\/span><\/h4>";//"<div class='money_sign'><span>$<\/span><\/div>";
    var numStr = num.toString();
    for(var i=0; i<numStr.length; i++){
        var numChar = numStr.charAt(i);
        numHTML += "<div class='numericimage_" + numChar + "'><span>" + numChar + "<\/span><\/div>";
    }
    return numHTML;
}

// Makes a basic URL-Slug from the lawyer name
function makeUrlSlug( lawyerName )
{
   return getFieldValue(lawyerName).replace(/ /g,"_").replace(".","");

}
// strips out any additional hlper dat from this value
function getFieldValue(value)
{
    return $.trim(String(value)).replace('$1$','').replace('$0$','').replace('$None$',''); // these last three are a hack to allow the python json list to return correctly

}

// Find by Name
function toggleSearch(state){
	if(state == "hide"){
		$("#name_panel").removeClass("visible");
	} else if(state == "show"){
		$("#name_panel").addClass("visible");
	} else {
		$("#name_panel").toggleClass("visible");
	}

    if( $('#name_panel').hasClass('visible'))
    {
        document.location.hash = "Find_By_Name";
        var partnerHtml = "";
        var otherHtml1 = '', otherHtml2 = '';
        var lastOther = 0;
        $.each(Lawyers.fields, function(i) {
            if( Lawyers.fields[i].indexOf('$1$') > -1 )
                partnerHtml += "<a href='#" + makeUrlSlug(Lawyers.fields[i]) + "' rel='" + i + "' class='lawyer_thumb'>" + getFieldValue(Lawyers.fields[i])+ "</a>";
            else
            {
                if( lastOther == 1)
                {
                    lastOther = 2;
                    otherHtml2 += "<a href='#" + makeUrlSlug(Lawyers.fields[i]) + "' rel='" + i + "' class='lawyer_thumb'>" + getFieldValue(Lawyers.fields[i])+ "</a>";
                } else {
                    lastOther = 1;
                    otherHtml1 += "<a href='#" + makeUrlSlug(Lawyers.fields[i]) + "' rel='" + i + "' class='lawyer_thumb'>" + getFieldValue(Lawyers.fields[i])+ "</a>";
                }
            }
        });
        $('.find_partners span').html(partnerHtml);
        $('.find_council span').html(otherHtml1);
        $('.find_assc span').html(otherHtml2);
    }
}

function pullStory(theStory){
    $("#lawyer_story .content").html(theStory);

    $("#lawyer_story").removeClass("loading");
    $("#lawyer_story .content").fadeIn();
}

// Pull Tweets
function pullTweets(twitterID){
    var tweetAmt = 5;
    var TweetHTML = "";
    var tweeturl = "http://twitter.com/statuses/user_timeline/" + twitterID + ".json?count=" + tweetAmt + "&callback=?";

    $.ajax({
        url: tweeturl,
        cache: false,
        dataType: "json",
        timeout: 2000,
        success: function(d){
            $.each(d, function(i, item){
                TweetHTML += "<ul><li>";
                TweetHTML += "<span class='text'>" + item.text + "<\/span>";
                TweetHTML += "<span class='date'>" + item.created_at + "<\/span>";
                TweetHTML += "<\/li>";
            });

            TweetHTML += "<\/ul>";
            $("#lawyers_tweets .content").html(TweetHTML);
            $("#lawyers_tweets").removeClass("loading");
            $("#lawyers_tweets .content").fadeIn();
        },
        error: function(XHR, textStatus, errorThrown){
            TweetHTML += "<h2>Twitter is DOWN :( " + textStatus + ", " + errorThrown +"<\/h2>";
            $("#lawyers_tweets .content").html(TweetHTML);
            $("#lawyers_tweets").removeClass("loading");
            $("#lawyers_tweets .content").fadeIn();
        }
    });
}


// Need "Job Title" within /feeds/lawyers/ to dynamically build search panel!
function buildSearchPanel(items){
	//#name_panel .find_partners .find_council .find_assc
}

var glob_carousel;
var locationHash = 1;

function historyCallBack(hash){
	if(hash){
		//var currentPageNum = hash.split("_")[1];
		//locationHash = parseInt(currentPageNum);
        // look up the index by the hash value

        var index = 0;
        for( var i = 0; i < lawyerIndexArray.length && index == 0; i++ )
            if( getFieldValue(lawyerIndexArray[i]) == hash)
                index = i;

        //var parts = hash.split("_");
        //locationHash = parseInt(parts[parts.length-1]);
        locationHash = index + 1;
	}
}

$(document).ready(function(){
	$.get(
		'/feeds/lawyers/',
		{},
		function(items) {
            Lawyers = items[0];
            var thumbsHTML = "<table cellspacing='0' cellpadding='0' border='0'><tr>";
			for(var i=1; i<=items[0].size; i++){
                var value = getFieldValue(items[0].fields[i]);
                var slug =  makeUrlSlug(value);
				thumbsHTML += "<td><a href='#" + slug + "' class='lawyer_thumb' id='lawyer_thumb_" + i + "' rel='" + i + "' title='" + value + "'></a></td>";
                lawyerIndexArray[lawyerIndexArray.length] = slug;
			}
			
			thumbsHTML += "</tr></table>";
			$("#carousel_thumbs").html(thumbsHTML);
			$("a[title]", "#carousel_thumbs").qtip({
				style: {
					name: 'kestyle',
					tip: true
				},
				position: {
					corner: {
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					}
				}
			});
			// Initialize history plugin.
			if(!ie6){
				$.historyInit(historyCallBack);
			}

            glob_carousel = $('#carousel_lawyers').jcarousel({
				scroll: 1,
				//wrap: "circular",
				start: locationHash,
				size: Lawyers.size,
				initCallback: carousel_initCallback,
				itemLoadCallback: carousel_itemLoadCallback,
				itemVisibleInCallback: {
					onBeforeAnimation: hideAllModules
					//onAfterAnimation: loadBioModules
				},
				itemVisibleOutCallback: {
					onBeforeAnimation: loadBioModules
					//onAfterAnimation: loadBioModules
				},
				//itemVisibleInCallback: hideAllModules,
				//itemVisibleOutCallback: loadBioModules,
				buttonNextHTML: "<a href='#' onclick='javascript: return false;'></a>",
				buttonPrevHTML: "<a href='#' onclick='javascript: return false;'></a>"
			});
		},
		'json'
	);
	
	$("#toggle_search").bind("click", function(e){
		toggleSearch();
		return false;
	});
	$("#close_panel").bind("click", function(e){
		toggleSearch();
		return false;
	});
	
});

