/**
 * Before run these functions you must initialize global variables:
 * var dataset = string; // this is a name of cookie to store identifiers of selected items
 * var compare_page = string; // an URL of a page where selected items are displayed
 * var gl_domain = string; // you can define a domain for cookie; if it is undefined, a default one will be used
 * var sIdPrefix = 'fav_'; // string prefix before a numeric id of an item to add to a favorites cookie
 *
 * In a html code you need to include these elements:
 * id="fav_msg" - place for a message containing a number of selected items and a link to a comparison page
 * id="fav_123", where 123 - any numeric id of an item to add to a favorites cookie and "fav_" - is equal to var sIdPrefix
 **/

if (!dataset) {
	var dataset = 'favoriteslite';
}
if (!compare_page) {
	var compare_page = '';
}
if (!sIdPrefix) {
	var sIdPrefix = 'fav_';
}

function update_fav(obj) {
	// the last char of a class name if '0' or '1'; it shows us whether 'favorites mark' unchecked or checked
	// For example: 'class="fav_place ch_0"' - two classes for an element, but the last char is a digit '0'
	var sLastChar = obj.className.charAt(obj.className.length-1);
	// 'favorites mark' has id like 'fav_123'; after '_' we has a numeric id of an object to add to a favorites cookie
	// 'fav_' - any string, it may be an empty string '' so id may be like '_123' or even just like '123' without '_' before digits
	// find the numeric id
	var nFavIdOffset = sIdPrefix.length;
	var nFavId = obj.id.substring(nFavIdOffset,obj.id.length);
	if (sLastChar=='0') {
		add_to_fav(nFavId);
		update_fav_place(obj,'1');
	}
	if (sLastChar=='1') {
		del_from_fav(nFavId);
		update_fav_place(obj,'0');
	}
}


/**
 * Change how a 'favorites mark' looks like - change the last char in the class name
 * by replacing the last char with the parameter 'checked', usually it is '0' or '1'
 **/
function update_fav_place(obj,checked) {
	sNewClassName = obj.className.substring(0,obj.className.length-1) + checked;
	obj.className = sNewClassName;
}


function add_to_fav(obj_id) {
	var sCartCookie = getCookie(dataset);
	var aCart = new Array();
	var aCartNew = new Array();
	var update_flag= true;
	if (sCartCookie==null) {
		aCartNew.push(obj_id);
	} else {
		aCart=sCartCookie.split(',');
		for (var i = 0; i < aCart.length; i++) {
			if (aCart[i]==obj_id) update_flag = false;
			if (aCart[i].length>0) aCartNew.push(aCart[i]);
		}
		if (update_flag) {
			aCartNew.push(obj_id);
		}
	}
	if (update_flag) {
		setCookie(dataset, aCartNew.join(','));
		cart_count=aCartNew.length;
	}
	update_fav_msg ();
}

function del_from_fav(obj_id) {
	var sCartCookie = getCookie(dataset);
	var aCart = new Array();
	var aCartNew = new Array();
	var update_flag= false;
	if (sCartCookie!=null) {
		aCart=sCartCookie.split(',');
		for (var i = 0; i < aCart.length; i++) {
			if (aCart[i]!=obj_id && aCart[i].length>0) {
				aCartNew.push(aCart[i]);
			} else {
				update_flag= true;
			}
		}
	}
	if (update_flag) {
		cart_count=aCartNew.length;
		if (cart_count==0) {
			setCookie(dataset, '', 'Thu, 01-Jan-70 00:00:01 GMT');
		}
		else {
			setCookie(dataset, aCartNew.join(','));
		}
	}
	update_fav_msg ();
}


/**
 * очистить список
 **/
function empty_fav(){
	setCookie(dataset, '', 'Thu, 01-Jan-70 00:00:01 GMT');
	if (document.getElementsByTagName){
		var aSpans = document.getElementsByTagName("span");
		// loop through all span tags and look for id begins with sIdPrefix
		for (var i=0; i<aSpans.length; i++){
			var oSpanTag = aSpans[i];
			if (oSpanTag.id.indexOf(sIdPrefix)!=-1){
				update_fav_place(oSpanTag,'0');
			}
		}
	}
	cart_count=0;
	update_fav_msg ();

}


function update_fav_msg () {
	var sMsg='&nbsp;';
	var sCartCookie = getCookie(dataset);
	if (cart_count>0) {
		var sWord1=formatWord(cart_count,'отмечен','','о','о');
		var sWord2=formatWord(cart_count,'тур','','а','ов');
		var sEmptyCart = '';
		if (document.getElementsByTagName){
			sEmptyCart = '; <a href="javascript:empty_fav();">очистить список</a>';
		}
		sMsg='<i>('+sWord1+' '+cart_count+' '+sWord2+sEmptyCart+')</i> :: <b><a href="'+compare_page+
		'?a=b&tourslist='+sCartCookie+'" class="a_compare">посмотреть выбранные</a></b>&nbsp;::';
	}
	var msgElm1 = (document.all) ? document.all['fav_msg'] : document.getElementById('fav_msg');
	var msgElm2 = (document.all) ? document.all['fav_msg_2'] : document.getElementById('fav_msg_2');
	if (msgElm1) msgElm1.innerHTML=sMsg;
	if (msgElm2) msgElm2.innerHTML=sMsg;
}

function formatWord (num,wordroot,end1,end2,end3) {
	var temp=end3;
	var last=num+"";
	if (num>20)
	last=last.substr((last.length-1),last.length);
	if (last==1) temp=end1;
	if (last==2 || last==3 || last==4) temp=end2;
	return (wordroot+temp);
}


function getCookie(name) {
	var sCookie = " " + document.cookie;
	var sFind = " " + name + "=";
	var sValue = null;
	var offset = 0;
	var end = 0;
	if (sCookie.length > 0) {
		offset = sCookie.indexOf(sFind);
		if (offset != -1) {
			offset += sFind.length;
			end = sCookie.indexOf(";", offset)
			if (end == -1) {
				end = sCookie.length;
			}
			sValue = unescape(sCookie.substring(offset, end));
		}
	}
	return(sValue);
}


function setCookie (name, value, expires, path, domain, secure) {
	if (!expires) {
		var oDate = new Date();
		oDate.setHours(oDate.getHours()+24*30);
		expires=oDate.toGMTString();
	}
	if (!path)  path="/";
	//if (!domain) { domain = gl_domain ? gl_domain : '';}
	document.cookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}



/**
 * Начальные установки
 **/
function init_fav_places(){
	if (!document.getElementsByTagName){ return; }

	var sCartCookie = getCookie(dataset);
	var aCart = new Array();
	var aCartChecked = new Array();
	cart_count=0;
	if (sCartCookie!=null) {
		aCart=sCartCookie.split(',');
		for (var i = 0; i < aCart.length; i++) {
			if (aCart[i].length>0) {
				aCartChecked[aCart[i]] = 1;
				++cart_count;
			}
		}
		update_fav_msg ();
	}



	var aSpans = document.getElementsByTagName("span");
	var nOffset = sIdPrefix.length;
	// loop through all span tags and look for id begins with sIdPrefix
	for (var i=0; i<aSpans.length; i++){
		var oSpanTag = aSpans[i];
		if (oSpanTag.id.indexOf(sIdPrefix) != -1){
			var nFavId = oSpanTag.id.substring(nOffset,oSpanTag.id.length);

			if (aCartChecked[nFavId]) {
				update_fav_place(oSpanTag,'1');
			}
			else {
				update_fav_place(oSpanTag,'0');
			}
		}
	}


	return true;
}



function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}



addLoadEvent(init_fav_places);	// run  onLoad




