$(document).ready(onDocumentReady_workAjax);

var filterArray = [branch_id];

var orderby = "default";
var categorie = branch_id;
var paginationNum = "P0";
var current_request;
var currentsort;

function onDocumentReady_workAjax(){

	$("#btnThumbs").bind("click", onShowThumbsClicked);
	$("#btnList").bind("click", onShowListClicked);
	
	// Filter | default =  view all
	if ($.cookie("filterstring")) {
		// our filtercookie exists, so restore filter selected by user
		var cat_sel = $.cookie('filterstring');
		filterArray = cat_sel.split("_");
		//alert("filterArray= " + filterArray);
		categorie = cat_sel;
	}
	
	/* ----- FILTER BY CATEGORIES -----  */
	// Filter cases by categories
	$(".filter_list li").not(".filter_header").click(onFilterItemClicked);	


	/* ----- SORT (by date(default), title or client name) -----  */
	if ($.cookie("currentSorting")) {
		orderby = $.cookie("currentSorting");
		//alert("orderby: " + orderby);
		currentsort = $("#sortlist li a[rel='" + orderby + "']");
		currentsort = currentsort.parent();
		//alert(currentsort);
	}else{
		currentsort = $("#sortlist li:nth-child(2)");
	}	
	currentsort.addClass("current");
	
	// add click action to the sort fields (Data, Title, Client)
	$("#sortlist li").not(":first").click(onSortFilterClicked);	
	// ------------------
	
	
	if ($.cookie("currentpaginationNum")) {
		//alert("found cookie pageNum: " + $.cookie("currentpaginationNum"));
		paginationNum = $.cookie("currentpaginationNum");
	}
	
	
	// The value of the session cookie ; 1/true means thumb view is enabled
	if (!$.cookie('thumb_view') == 1) {
		//First time here, no cookie, show thumbs and hide list onload
		$.cookie('thumb_view', 1);		
	}

	// ------------------
	
	// attach functions to thumbs:
	initThumbs();
	initPagination();
	
	loadContent();
	
}

function onShowThumbsClicked(event){
	event.preventDefault();
	paginationNum = "P0";
	showThumbs();
}

function onShowListClicked(event){
	event.preventDefault();
	paginationNum = "P0";
	showList();
}

function onSortFilterClicked(event) {
	event.preventDefault();
	if (!$(this).hasClass("current")){
		$(this).addClass("current");
		currentsort.removeClass("current");
		currentsort = $(this);
		orderby = $(this).find("a:first").attr("rel");
	}else{
		$(this).removeClass("current");
		orderby = "default";
		currentsort = $("#sortlist li:nth-child(2)");
		currentsort.addClass("current");
	}
	
	$.cookie("currentpaginationNum", "P0");
	paginationNum = "P0";
	
	$.cookie("currentSorting", orderby);			   
	
	loadContent(getFilterString(), orderby)										   		
}

function onFilterItemClicked(event){
	event.stopImmediatePropagation();
	event.preventDefault(); 

	var filterby = $(this).find("a:first").attr("rel");
	
	// toggle button:
	if ($(this).hasClass("current")){
		$(this).removeClass("current");
	}else{
		$(this).addClass("current");
	}
	
	$(".filter_list li.filter_all").removeClass("current");

	updateFilterArr(filterby);
	
	if ($(this).hasClass("filter_all")){
		// reset filter; show all cases
		resetFilter($(this));
		categorie = branch_id;
		setFilterCookie(branch_id);
	}else{
		categorie = getFilterString();
		setFilterCookie(filterby);
	}
	
	$.cookie("currentpaginationNum", "P0");
	paginationNum = "P0";
	
	loadContent();
}

function showThumbs(){
	$("#work_list_view").hide();
	$("#work_thumb_view").customFadeIn("slow");
	$("#btnList").removeClass("current");
	$("#btnThumbs").addClass("current");
	$.cookie('thumb_view', 1);
}

function showList(){
	$("#work_thumb_view").hide();
	$("#work_list_view").customFadeIn("slow");
	$("#btnThumbs").removeClass("current");
	$("#btnList").addClass("current");
	$.cookie('thumb_view', 0);
}

function initPagination(){
	$("#pagination li a").bind("click", onPaginationLinkClicked);
}

function onPaginationLinkClicked(event){
	event.preventDefault(); 
	var urlArr = $(this).attr("href").split("/");
	
	paginationNum = urlArr[urlArr.length -2];
	$.cookie("currentpaginationNum", paginationNum);	
	loadContent();
	
	// back to top of page
	$('html, body').animate({scrollTop:100}, 400);
}

function updateFilterList() {
	//alert("updatefileter");
	$(".filter_list li").not(".filter_header").each(function() {
			// find matching menu item	
			var searchString = $(this).find("a:first").attr("rel");
			var arrayIndex = filterArray.findIndex(searchString);

			if (arrayIndex != null || (searchString == "all" && filterArray[0] == branch_id && filterArray.length == 1)) {
				//alert(arrayIndex + " :  " + searchString + " : " + filterArray);	
				$(this).addClass("current"); 
			} 

		
	});

}

	
function resetFilter(me) {
	filterArray = [branch_id];
	$(".filter_list li").not(".filter_header").each(

		// reset state
		function(){
			$( this ).removeClass("current");	 			
		}
					 			
	);		
	me.addClass("current");
}							
							
							
function setFilterCookie(filterby) {
	
	
	if ($.cookie("filterstring")) {
		$.cookie('filterstring',getFilterString());
	} else {
		$.cookie('filterstring',filterby);
	}
	//alert("cookie filterstring= "+$.cookie('filterstring'));
	//return getFilterString();

}

function updateFilterArr(filterby){
	//alert ("gst:updateFilterArr = " + filterby) 
	if (filterby == branch_id){
		filterArray = [branch_id];
		return
	}
	
	var arrayIndex = filterArray.findIndex(filterby);
	if (arrayIndex != null) {
	
		filterArray.splice(arrayIndex,1);
		//alert("(String(filterArray) == String([branch_id]))::" + (String(filterArray) == String([branch_id])));
		
		//filter is current branch? select 'view all'
		if (String(filterArray) == String([branch_id])){ 
			$(".filter_list li:first").addClass("current");
		}

	} else {
		filterArray.push(filterby);
	}
	//alert ("filterArray after= " + filterArray) 
}

function getFilterString(){
	if (filterArray.length == 0) {
		var filterstring = "";
	} else {
		var filterstring = filterArray.join("_");// ex 1_2_3
	}
	//alert ("getFilterString" + filterstring)
	return filterstring;
}

function toggleThumbView(){
	
	//Next time, check cookie
	if ($.cookie('thumb_view') == 1) {
		showThumbs();
	}else{
		showList();
	}
}


function initThumbs(){
	$("dl").hover(onOverThumbItem, onOutThumbItem); 
	$("dl").bind("click", onThumbItemClicked);
}

function onThumbItemClicked(e){
	var clickedId = jQuery(this).attr("entry_id");
	//alert(clickedId);
	$.cookie("lastEntry", clickedId, {path:"/"});
	window.location=$(this).find("a").attr("href"); 
	return false;
}

function onOverThumbItem(){
	var bgColor = $(this).find("a:first").attr("rel");
	if (bgColor == ""){
		bgColor = "#e52525";
	}
	
	$(this).animate({backgroundColor:"#e52525", color:"#f08383"}, {queue:false,duration:500});
	$(this).children("dd.project_client").animate({color:"#f08383"}, {queue:false,duration:500});
	$(this).children("dd:last").animate({color:"#FFFFFF"}, {queue:false,duration:500});
	$(this).addClass("active");
}

function onOutThumbItem() { 
	$(this).animate({backgroundColor:"#fcfcfc", color:"#636363"}, {queue:false,duration:500});
	$(this).children("dd.project_client").animate({color:"#636363"}, {queue:false,duration:500});
	$(this).children("dd:last").animate({color:"#e52525"}, {queue:false,duration:500});
	$(this).removeClass("active");
}
	
/**
 * function is called from the work.index.php page
 * @param cat_id
 * @return
 */
function initCatMenu(cat_id) {
	//clear the pages cookie
	$.cookie("currentpaginationNum", null);
	paginationNum = "P0";
	$.cookie("filterstring", null);
	
	//alert("catId: " + cat_id);
	
	$(".filter_list li a[rel="+ cat_id+ "]").parent().addClass("current");
	filterArray = [branch_id];
	updateFilterArr(cat_id);
	categorie = getFilterString();
	setFilterCookie(cat_id);
	loadContent();
}

function loadContent() {
	//alert("loadContent= " + orderby);
	var page = base_url + "index.php/work/ajax_selection";
	
	// we need a string like this: ajax_selection/category='61'/orderby='client|date'/sort='asc|desc'
	//alert (user_location + " : " + paginationNum);

	page = page+"/category='"+categorie+"'";
	
	if (orderby != "default") {
		page = page+"/orderby='"+orderby+"|date'/sort='asc|desc'";
	}
	
	if (paginationNum != "P0") {
		page = page+"/"+paginationNum;
	}
	
	if(group_id == 1){
		page = page + "/admin";	
	}
	
	//alert("page: " + page);
	

	loadPage(page);
	
	$('#load').remove();
	$('#contentarea').append('<span id="load">LOADING...</span>');
	$('#load').fadeIn('normal');
}

function loadPage(page) {
	try{
		current_request.abort();
	}catch(e){
		//alert("abort failed");
	};

	$('#work_selection').hide('fast');
	//alert("page: " + page);
	current_request = $.ajax({url: page, success: onLoadPageSucces});
}

function onLoadPageSucces(data){
	$('#work_selection').html(data); 
	showNewContent();
	//getAllEntryIdsForFilter();
	
	toggleThumbView();
}
/*
function getAllEntryIdsForFilter() {
	var page = base_url + "index.php/work/ajax_get_all_entry_ids_for_filter";
	
	// we need a string like this: ajax_selection/category='61'/orderby='client|date'/sort='asc|desc'
	//alert (user_location + " : " + paginationNum);

	if (categorie != branch_id) {
		page = page+"/category='"+categorie+"'";
	}

	if (orderby != "default") {
		page = page+"/orderby='"+orderby+"|date'/sort='asc|desc'";
	}
	
	current_request = $.ajax({url: page, success: onLoadEntryIdsSucces});
}

function onLoadEntryIdsSucces() {
	//$('#work_selection').html(data); 
}
*/
function showNewContent() {
	hideLoader();
	$('#work_selection').customFadeIn("fast");
	toggleThumbView();
	initThumbs();
	initPagination();
}

function hideLoader() {
	$('#load').fadeOut('normal');
}


Array.prototype.findIndex = function(value) {
	var ctr = null;
	for (var i = 0; i<this.length; i++) {
		// use === to check for Matches. ie., identical (===), ;
		if (this[i] == value) {
			return i;
		}
	}
	return ctr;
};