var domainname = location.hostname.replace(new RegExp('^[a-z]+', 'i'), '');
var cookieName = "LC-compare";
var xCall = '';
// needed to fix bg image bug	
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

function gi(id) {
	return document.getElementById(id);
}
function tn(tagname) {
	return document.getElementsByTagName(tagname);
}
function init() {
}
$(function() {
	//getFontSize();
	checkCompare();
	//initClickHeat(); 
	addPulldown('editmode');
	addPulldown('locales');
	$('.items .item .info').ellipsis();
	/*$('input#g_sw').autocomplete('/contribute.php?type=search&max=10', {
		formatItem: function(res, resnr, totalres, name, currentval) {
			return '<a href="/'+res[1]+'/">'+res[0]+'</a>';
		}, scroll:false, width: 250

	}).result(function(event, res) {
		$('.searchspinner').fadeIn('slow', function() {
			document.location.href = '/'+res[1]+'/';
		});
	}).bind("activate.autocomplete", function(e, d) { 
	});*/
});
function addPulldown(which) {
	var t;
	if ($('.pulldown.'+which)) {
		$('.pulldown.'+which).hover(
			function() {
				clearTimeout(t);
				$('.'+which).find('.pd-content').fadeIn(200);
			},
			function() {
				t = setTimeout(function() {$('.'+which).find('.pd-content').hide()}, 500); 
			}
		);
	}
}
function show(id,style) {
	$('#'+id).show();
}
function hide(id) {
	$('#'+id).hide();
}
function toggleShow(id,style, id2, style2) {
	var obj = gi(id);
	if (obj) {
		if (obj.style.display != style) {
			$('#'+id).show();
			$('#'+id2).hide();
			hide(id2);
		} else {
			$('#'+id).hide();
			$('#'+id2).show();
		}
	}
}
var emailRe = new RegExp("^\\s*[\\w\\.\\-]+\\@([\\w\\-]+\\.)+[\\w\\-]+\\s*$");
function isValidEmail(str) {
	   return str.match(emailRe);
}
function isValidBirthDate(datestr) {
	if (!datestr) {
		return true;
	} 
	return isDate(datestr);
}
function isDate(str){
	var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/
	if (!re.test(str)) return false;
	var result = str.match(re);
	var y = parseInt(result[3]);
	var m = parseInt(result[2]);
	var d = parseInt(result[1]);
	if(m < 1 || m > 12 || y < 1900 || y > 2100) return false;
	if(m == 2){
		  var days = ((y % 4) == 0) ? 29 : 28;
	}else if(m == 4 || m == 6 || m == 9 || m == 11){
		  var days = 30;
	}else{
		  var days = 31;
	}
	return (d >= 1 && d <= days);
}
/*  For use on review input page */
function searchRedir(sq_el) {
	var sq = sq_el.value;
	sq = sq.replace(/[^-0-9a-zA-Z ]/g, ' ');
	sq = sq.replace(/\s+/g, ' ');
	sq = sq.replace(/^\s/, '');
	sq = sq.replace(/\s$/, '');

	sq_el.value = sq;

	if (sq) {
		document.location.href='/q/' + sq + '/';
	}
	return false;
}
function checkItems() {
	var error=0;
    // Check empty arguments
    for(var i=1; i<arguments.length; i++) {
		var curInpArg = '#'+arguments[0]+' input[rel='+arguments[i]+']';
		var curTAArg = '#'+arguments[0]+' textarea[rel='+arguments[i]+']';
		if ($(curInpArg).val() || $(curTAArg).val()) {
			if (arguments[i] == 'email') {
				var e1 = $('#'+arguments[0]+' input[name=email]').val();
				var e2 = $('#'+arguments[0]+' input[name=email2]').val();
				if ($('#'+arguments[0]+' input[name=email2]').length > 0) {
					if (!isValidEmail( e1 ) && !isValidEmail( e2 )) {
						$(curInpArg).addClass('error');
						error++;
					} else if (e1 != e2) {
						$(curInpArg).addClass('error');
						error++;
					} else if (e1.length < 5) {
						$(curInpArg).addClass('error');
						error++;
					}
				} else {
					if (!isValidEmail( e1 )) {
						$(curInpArg).addClass('error');
						error++;
					} else if (e1.length < 5) {
						$(curInpArg).addClass('error');
						error++;
					}
				}
			} else if (arguments[i] == 'date_of_birth' && !isValidBirthDate( $(curInpArg).val() )) {
				$(curInpArg).addClass('error');
				error++;
			} else if (arguments[i] == 'password') {
				var pw1 = $('#'+arguments[0]+' input[name=password]').val();
				var pw2 = $('#'+arguments[0]+' input[name=password2]').val();
				if (pw1 != pw2) {
					$(curInpArg).addClass('error');

					error++;
				} else if (pw1.length < 5) {
					$(curInpArg).addClass('error');
					error++;
				} else {
					$(curInpArg).removeClass('error');
				}
			} else {
				$(curInpArg).removeClass('error');
			}
		} else {
			$(curInpArg).addClass('error');
			$(curTAArg).addClass('error').focus();
			error++;
		}
	}
    return (error > 0) ? false : true;
}
function checkCB(check,id) {
	formI = gi('formitem_'+id);
	if (check == false) {
		formI.className='disabled formitem';
		gi('slider_value_'+id).value='';
		$('.slide_' + id).slider('disable');
	} else if (check == true) {
		formI.className='formitem';
		gi('slider_value_'+id).value='6';
		$('.slide_' + id).slider('enable');
	}
}
function setCompareCookie(items) {
	var expires = new Date();
	var today = new Date();
	expires.setTime(today.getTime() + 60*60*24*1000); // 
	if (items != null && items[0] != null) {
		cookie = items.join(";");
		cookie = cookie.substr(0,3000);
	} else {
		cookie = '';
	}
	document.cookie = cookieName + "=" + escape(cookie) + '; path=/' + ((expires == null) ? "" : ("; domain=" + domainname + "; expires=" + expires.toGMTString()));
}
function removeCompareCookie() {
	var expires = new Date();
	var today = new Date();
	expires.setTime(today.getTime() - 100000); 
	document.cookie = cookieName + "=" + escape('remove') + '; path=/' + ((expires == null) ? "" : ("; domain=" + domainname + "; expires=" + expires.toGMTString()));
}

function getCompareCookie() {
	var search = cookieName + "=";
	if (document.cookie.length > 0) { // if there are any cookies
		offset = document.cookie.indexOf(search) ;
		if (offset != -1) { // if cookie exists 
			offset += search.length ;
			// set index of beginning of value
			end = document.cookie.indexOf(";", offset) ;
			// set index of end of cookie value
			if (end == -1) {
				end = document.cookie.length;
			}
			return unescape(document.cookie.substring(offset, end));
		}
	}
}
function getItems(oldCookie) {
	var items = null;
	if (oldCookie != null && oldCookie.indexOf('|')>-1) {
		items = oldCookie.split(";");
	}
	return items;
}
function removeItem(oldItems, item) {
	if (oldItems != null) {
		var newItems = new Array();
		for (i=oldItems.length-1; i>=0; i--) {
			var curItem = ((oldItems[i]).split("|"))[0];
			if (curItem != item) {// && (newItems.join(";")+item).length<3000) {
				newItems[newItems.length] = oldItems[i];
			}
		}
		newItems.reverse();

		var e = document.getElementById(item);
		if (e != null)
			e.checked = false;
	}
	return newItems;
}

function addItem(oldItems, item, name) {
	var newItems = new Array();
	if (oldItems != null) {
		for (i=oldItems.length-1; i>=0; i--) {
			if ((oldItems[i]).indexOf("|")>-1) {
				var curItem = ((oldItems[i]).split("|"))[0];
				if (curItem != item){
					newItems[newItems.length] = oldItems[i];
				}
			}
		}
		newItems.reverse();
		if (newItems.length < 6) 
			newItems[newItems.length] = item + '|' + name;
		else {
			alert(gi('errormsg_selections').innerHTML);	
			var e = document.getElementById(item);
			if (e != null)
				e.checked = false;
		}
	} else {
		newItems[0] = item + '|' + name;
	}
	return newItems;
}
function checkCompare() {
	var oldItems = getItems(getCompareCookie());
	var newItems = new Array();
	newItems = removeItem(oldItems, -1);
	printItems(oldItems);

}
function checkCompareItem(id, name, action) {
	var oldItems = getItems(getCompareCookie());
	var newItems = new Array();

	if (action == 'check') {
		newItems = addItem(oldItems, id, name);
	} else if (action=='uncheck') {
		newItems = removeItem(oldItems, id);
	} else {
		newItems = oldItems;
	}
	setCompareCookie(newItems);
	printItems(newItems);
}
function printItems (Items) {
	var o;
	var o2;
	o = '';
	o2 = '';
	o3 = '';
	if (Items) {
		for (i=Items.length-1; i>=0; i--) {
			var curItem = (Items[i]).split("|");
			o += '<li id="li_' + curItem[0] + '"><a onclick="checkCompareItem(\''+curItem[0]+'\',\'-\',\'uncheck\');" class="closeicon"></a> ' + unescape(curItem[1])  + '</li>';
			if (gi('form_hidden_fields')) {
				o2 += '<input type="hidden" name="js_clubs[]" value="' + curItem[0] + '"/>';
			}
			if (gi('form_hidden_fields_cl')) {
				o3 += '<input type="hidden" name="js_clubs[]" value="' + curItem[0] + '"/>';
			}
			if (gi(curItem[0])) {
				gi(curItem[0]).checked=true;
			}
		}
		if (Items.length > 1) {
			$('#cl_compare').show();
		} else {
			$('#cl_compare').hide();
		}
	}
	if (gi('compare_list_ul')) {
		gi('compare_list_ul').innerHTML = o;
		if (gi('form_hidden_fields')) {
			gi('form_hidden_fields').innerHTML = o2;
		}
		if (gi('form_hidden_fields_cl')) {
			gi('form_hidden_fields_cl').innerHTML = o3;
		}
		$('#compare_list').show();
		$('#compare_list_ul').show();
	}
	if (!o || o == '') {
		if (gi('form_hidden_fields')) {
			gi('form_hidden_fields').innerHTML = '';
		}
		$('#compare_it').hide();
		$('#cl_compare').hide();
		$('#compare_list_ul').slideUp('slow');
	} else {
		$('#compare_list_ul').show();
		$('#compare_it').slideDown('slow');
	}
}
function initBlock(id, action) {
	if (action == 'close') {
		animateBlock(id,130, 200, 'small')
	} else if (action == 'open') {
	} else {
	}
	
}
function animateBlock(id, width, height, action) {
	w_org = gi(id).offsetWidth;
	h_org = gi(id).offsetHeight;
	if (action == 'small') {
		step = Math.round((w_org - width) * 0.2);
		if (h_org >= height) {
			gi(id).style.height = (h_org - step) + 'px';
		}
		if (w_org >= width) {
			gi(id).style.width = (w_org - step) + 'px';	
		}
		if (w_org >= width || h_org >= height) {
			setTimeout("animateBlock('"+id+"','"+width+"','"+height+"','"+action+"')",10);
		} else {
		}
	}
}
function setFontSize(px) {
	var x = 0;
	if (px == '11px') {
		x = '-18px';
	} else if (px == '12px') {
		x = '-37px';
	}
	if (px && px != '') {
		gi('fs_10px').style.backgroundPosition = '';
		gi('fs_11px').style.backgroundPosition = '-18px 0px';
		gi('fs_12px').style.backgroundPosition = '-37px 0px';
		tn('body')[0].style.fontSize=px;
		setCookie('fontSize', px,100);
		gi('fs_'+px).style.backgroundPosition = x + ' -21px';
	}
}
function getFontSize() {
	var px = getCookie('fontSize');
	if (!px) {
		px = '10px';
	}
	setFontSize(px);
}
function setCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString()+";path=/;domain="+domainname;
}
function getCookie(fontCookieName) {
	var search = fontCookieName + "=";
	if (document.cookie.length > 0) { // if there are any cookies
		offset = document.cookie.indexOf(search) ;
		if (offset != -1) { // if cookie exists 
			offset += search.length ;
			// set index of beginning of value
			end = document.cookie.indexOf(";", offset) ;
			// set index of end of cookie value
			if (end == -1) {
				end = document.cookie.length;
			}
			return unescape(document.cookie.substring(offset, end));
		}
	}
}
function enablePopup(which, w, h, txt) {
	if ($('#IE6').size() > 0) {
		$('#'+which).slideDown('fast', function() {
			$('#'+which+' form').prepend('<a onclick="$(\'#'+which+'\').slideUp(\'fast\', function() {$(\'#popup_overlay\').fadeOut(0);});" class="close">'+txt+'<span class="closeicon"></span></a>');
		});
	} else {
		$('#popup_overlay').fadeIn(0, function() {
			$('#'+which).slideDown('fast', function() {
				$('#'+which+' form').prepend('<a onclick="$(\'#'+which+'\').slideUp(\'fast\', function() {$(\'#popup_overlay\').fadeOut(0);});" class="close">'+txt+'<span class="closeicon"></span></a>');
			});
		});
	}

}
function saveRegionInfoText(lang_id, region_id, shorttxt,fulltxt) {
	$('#regioninfo').append('<img src="//www.leadingcourses.com/img/loading.gif" class="spinner" alt="" style="width: 20px;height: 20px;position: relative;z-index: 1000;vertical-align: middle;"/>');
	$.ajax({
		type: "POST",
		url: "/contribute.php",
		data: ({pagetype:'lister',action:'saveRegionInfoText',shorttext:shorttxt,fulltext:fulltxt,region_id:region_id,lang_id:lang_id}),
		dataType: "text",
		success: function(msg) {
			$('img.spinner').remove();
		},
		error: function(id,msg) {
			alert('error: '+msg);
		}

	});
}
function setHomeClub(club_id) {
	$('#home_course a').append('<img src="//www.leadingcourses.com/img/loading.gif" class="spinner" alt="" style="width: 20px;height: 20px;position: relative;z-index: 1000;vertical-align: middle;"/>');
	$.ajax({
		type: "POST",
		url: "/contribute.php",
		data: ({pagetype:'detail',action:'setHomeClub',home_club:club_id}),
		dataType: "html",
		success: function(msg) {
			$('#home_course').html(msg);
		},
		error: function(msg) {
			alert('error: '+msg);
		}

	});
}
function removeHomeClub(club_id) {
	var confirmmsg = getTranslation('confirm_delete_home_club');
	if (confirm(confirmmsg)) { 
		$('#home_course').append('<img src="//www.leadingcourses.com/img/loading.gif" class="spinner" alt="" style="width: 20px;height: 20px;position: relative;z-index: 1000;vertical-align: middle;"/>');
		$.ajax({
			type: "POST",
			url: "/contribute.php",
			data: ({pagetype:'detail',action:'removeHomeClub',home_club:club_id}),
			dataType: "html",
			success: function(msg) {
				$('#home_course').html(msg);
			},
			error: function(msg) {
				alert('error: '+msg);
			}
		});
	}
}
function saveAttribute(val, att_id, type_id, id, type) {
	$('#show_value_'+id).prepend('<img src="//www.leadingcourses.com/img/loading.gif" alt="" style="width: 20px;height: 20px;position: relative;z-index: 1000;vertical-align: middle;"/>');
	$.ajax({
		type: "POST",
		url: "/contribute.php",
		data: "pagetype=detail&subtype="+type+"&action=save&value="+val+"&attribute_id="+att_id+"&type_id="+type_id+"",
		dataType: "text",
		success: function(msg) {
//			alert(''+msg);
			getClubAttribute(att_id,type_id,id,type)
		},
		error: function(id,msg) {
			alert('error: '+msg);
		}

	});
}
function getClubAttribute(att_id,type_id, id,type) {
	$.ajax({
		type: "POST",
		url: "/contribute.php",
		data: "pagetype=detail&subtype="+type+"&action=getAttribute&attribute_id="+att_id+"&type_id="+type_id+"",
		dataType: "text",
		success: function(msg) {
//			alert(''+msg);
			$('#show_value_'+id).html(msg).show(); // must be reset because loading image is prepended
		},
		error: function(id,msg) {
			alert('error: '+msg);
		}

	});
}
function transferSelectValues(select_id, input_id) {
	var vals = '';
	$('#'+select_id).find('option:selected').each( function() {
		vals += $(this).val()+';';
	});
	$('#'+input_id).val(vals);
}
function getUploadedPhotos(offset, rpp, total, type, visitor_id) {
	$.ajax({
		type: "POST",
		url: "/contribute.php",
		data: "pagetype=profile&subtype="+type+"&action=getPhotos&visitor_id="+visitor_id+"&rpp="+rpp+"&offset="+offset+"&total="+total+"",
		dataType: "text",
		success: function(msg) {
			$('#photos').html(msg);
		},
		error: function(id,msg) {
			alert('error: '+ msg);
		}
	});
	return false;
}
function getTranslation(short) {
	var ret = $.ajax({
		type: "GET",
		url: "/contribute.php",
		data: "type=translation&short="+short,
		dataType: "text",
		async: false
	}).responseText;
	return ret;

}
function getSearchData(sq,max) {
	var ret = $.ajax({
		type: "POST",
		url: "/contribute.php",
		data: "pagetype=search&searchword="+sq+"&max="+max+"",
		dataType: "text",
		success: function(msg,id) {
		},
		error: function(id,msg) {
		}
	});
	return ret;
}
function dropdown(which) {
	if ($('.pd-content').hasClass('active')) {
		$('.pd-content').slideUp(200);
		$('.pd-content').removeClass('active');
	} else {
		$('.pd-content').slideUp(0);
		$('.'+which+' .pd-content').slideDown(300, function() {
			$(this).addClass('active');
		});
	}

}
(function($) {
	$.fn.ellipsis = function(enableUpdating){
		var s = document.documentElement.style;
		if (!('textOverflow' in s || 'OTextOverflow' in s)) {
			return this.each(function(){
				var el = $(this);
				if(el.css("overflow") == "hidden"){
					var originalText = el.html();
					var w = el.width();
					
					var t = $(this.cloneNode(true)).css('position', 'absolute').hide()
					.css('width', 'auto').css('overflow', 'visible');
					el.after(t);
					
					var text = originalText;
					while(text.length > 0 && t.width() > el.width()){
						text = text.substr(0, text.length - 1);
						t.html(text + "...");
					}
					el.html(t.html());
					
					t.remove();
					
					if(enableUpdating == true){
						var oldW = el.width();
						setInterval(function(){
							if(el.width() != oldW){
								oldW = el.width();
								el.html(originalText);
								el.ellipsis();
							}
						}, 200);
					}
				}
			});
		} else return this;
	};
	$.fn.inlineSearch = function(searchElements, parentElements) {
		$(this).keyup(function() {
			var searchString = $(this).val();
			if (searchString.length > 0) {
				$(searchElements).parents(parentElements).slideUp(0);
				//$(searchElements+':contains(' +searchString+ ')').slideDown(20);
				$(searchElements).filter(':containsIgnoreCase(' +searchString+ ')').parents(parentElements).slideDown(0);
				$('search').css({'background-image':'none','background-position':'top right','background-repeat':'no-repeat'});
			} else {
				$(searchElements).parents(parentElements).show();
			}
		});
	}
	$.expr[':'].containsIgnoreCase = function(a,i,m){
		return $(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
	};

})(jQuery);
