/* favorites related */
var favorites = new Object();
favorites.cookieName = 'cookie_favorites';
favorites.sepPrefChar = '|';
favorites.sepSuffChar = ',';
favorites.pageItems = null;
favorites.msgWaitingSel = '#FavoritesList_MsgWaiting';
favorites.msgNoItemsSel = '#FavoritesList_MsgNoItems';
favorites.removeAllSel = '.fav-remove-all';
favorites.isListPage = false;

favorites.setListMsg = function(selSrc) {
	var objParent = $('.content-fav-list');
	objParent.html('');
	if(selSrc) {
		objParent.append('<div class="msg">'+$(selSrc).html()+'</div>');
	}
}
favorites.update = function() {
    // update controls visible on all pages
    $('#MenuLevel1Favorites .text').html('(' + favorites.count() + ')');
    if (favorites.isListPage) {
        // update controls and state on list page
        if (favorites.count() == 0) {
            favorites.setListMsg(favorites.msgNoItemsSel);
            favorites.pageItems = null;
            $(favorites.removeAllSel).hide();
        }
        else {
            $(favorites.removeAllSel).show();
            $(favorites.msgNoItemsSel).hide();
        }
    }
}
favorites.renderItems = function() {
	var objParent = $('.content-fav-list');
	
	if(favorites.pageItems==null || favorites.pageItems.length==0) {
		favorites.update();
		return;
	}
	
	favorites.setListMsg(null);
	
	var strRemoveFavText = $('#FavoritesList_RemoveItem').text();
	
	for(var i=0;i<favorites.pageItems.length;i++) {
		var strUrl = favorites.pageItems[i].LinkUrl;
		var strHtml = '<div class="item">'+
			'<h3><a class="icon" href="'+strUrl+'">'+favorites.pageItems[i].PageName+'</a></h3>'+
			'<a class="url" href="'+strUrl+'">'+strUrl+'</a>'+
			'<br /><a class="remove" href="#">'+strRemoveFavText+'</a>'+
			'<input type="hidden" value="'+favorites.pageItems[i].PageID+'" />'+
		'</div>';
		objParent.append(strHtml);
	}
	$('.content-fav-list .item').each(function() {
		var objItem = $(this);
		var strVal = $(this).children('input').attr('value');
		$(this).children('.remove').bind('click', function() {
			objItem.fadeOut(600, function() {
				objItem.remove();
				favorites.remove(strVal);
				favorites.update();
			});
			return false;
		});
	});

	favorites.update();
}

// setup favorites page, only needs to be loaded when on the favorites page. 
// Waist of performance otherwise
favorites.load = function() {
    
    var arrItems = favorites.getItems();
    if(arrItems==null || arrItems.length==0) {
		favorites.update();
		return false;
    }
    
    favorites.setListMsg(favorites.msgWaitingSel);
    
	var strValues = '';
	for (var i = 0; i < arrItems.length; i++) {
		strValues += arrItems[i] + favorites.sepSuffChar;
	}

	//var strJsonInData = "{'strPageIDs':'" + strValues + "'}";
	var strJsonInData = "{'strLanguageBranch':'" + EPI_CURRENT_LANG_CODE + "','strPageIDs':'" + strValues + "'}";
    
    $.ajax({
        type: "POST",
        url: common.miscServiceUrl + '/GetFavoritesData',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: strJsonInData,
        timeout: common.ajaxTimout,
        success: function(response) {
			var res = (typeof response.d == 'string') ? eval(response.d) : response.d;
			favorites.pageItems = res;
			favorites.renderItems();
        },
        error: function(msg, a, b) {
            alert('error, please reload the page and try again');
        }
    });    
}
favorites.getItems = function() {
    // make the cookies an array of identities
    var strValues = common.getCookieValue(favorites.cookieName) + '';
    if (common.isValue(strValues)) {
        var arr1 = strValues.split(favorites.sepSuffChar);
        var arr2 = [arr1.length-1];
        for (var i = 0; i < arr1.length; i++) {
            if (common.isValue(arr1[i])) {
                arr2[i] = arr1[i].replace(favorites.sepPrefChar, '');
            }
        }
        return arr2;
    }
    return null;
}
favorites.count = function() {
    // count the cookies
    var arrItems = favorites.getItems();
    if(arrItems != null) {
        return arrItems.length;
    }
    return 0;
}
favorites.remove = function(id) {
    var strValues = common.getCookieValue(favorites.cookieName);

    if (strValues == null) {
        return false;
    }

    var strNewValue = favorites.sepPrefChar + id + favorites.sepSuffChar;
    strValues = common.isValue(strValues) ? strValues : null;
    if (strValues != null) {
        if (strValues.indexOf(strNewValue) > -1) {
            strValues = strValues.replace(strNewValue, '');
        }
    }
    common.setCookie(favorites.cookieName, strValues);

    favorites.update();
    return false;
}
favorites.add = function(id) {
    // send in a id and save it to cookies
    var strValues = common.getCookieValue(favorites.cookieName);
    var strNewValue = favorites.sepPrefChar + id + favorites.sepSuffChar;
    strValues = common.isValue(strValues) ? strValues : null;

    if (strValues == null) {
        strValues = strNewValue;
    }
    else {
        if (strValues.indexOf(strNewValue) == -1) {
            strValues += strNewValue;
        }
    }

    common.setCookie(favorites.cookieName, strValues);
    favorites.update();

    return false;
}
favorites.initList = function() {
    favorites.isListPage = true;
    favorites.load();

    // Its the fav list page, we to override the default add-fav behavior, 
    // so the user can se update directly
    var objFavButton = $('.bottom-functions a.fav-add');
    objFavButton.unbind('click');
    objFavButton.bind('click', function() {
        favorites.add(EPI_CURRENT_PAGE_ID);
        favorites.load();
        return false;
    });


    $(favorites.removeAllSel).bind('click', function() {
        common.removeCookie(favorites.cookieName);
        favorites.update();
        return false;
    });
}
favorites.init = function() {
	// set click event
	$('.bottom-functions a.fav-add').bind('click', function() {
		return favorites.add(EPI_CURRENT_PAGE_ID);
	});
	
	$('#MenuLevel1Favorites')
	.show()
	.bind('click', function() {
		window.location.href = $(this).children('.text').attr('href');
		return false;
	});
	
	favorites.update();
}
$(document).ready(function() {
    favorites.init();
})

