var debug = true;

$(document).ready(function() {
	debugLog("common.document.ready()");
	initDocument();
});

function initDocument() {
	debugLog("common.initDocument()");
	$('a.popup, #menu_popup_login_htm a').click(function() {
		debugLog("common.a.click()");
		launchPopup($(this).attr('href'));
		return false;
	});
	



	if (typeof(initPage)=="function") initPage();
}

var div_loading = {};

function loadDiv(id,url,data,callback,issearch) {
	debugLog("common.loadDiv('"+id+"','"+url+"') div_loading[id]=["+div_loading[id]+"]");

	if (!div_loading[id]) {
		
		div_loading[id] = true;
	
		var height = $("#"+id).height();
		var overflow = $("#"+id).css('overflow');
		var html = $("#"+id).html();
	
		if (typeof(issearch)=='undefined') issearch = false;
	
		if (issearch) {
	
			$("#"+id).addClass('on').addClass('loading').css('overflow','hidden');
		
			$("#"+id).animate({
				height: '50px'
			}, 500, function() {
				// Animation complete.
				debugLog("common.loadDiv: animate complete");
				$("#"+id).html("<div class='searching'>Searching...</div>");
	
				$.ajax({
					url: url,
					type: "POST",
					data: data,
					cache: false,
					dataType: "html",
					success: function(data, textStatus, XMLHttpRequest){
						debugLog("common.loadDiv: ajax:"+issearch+" success");
						$("#"+id).height('auto').html(data).removeClass('loading').attr("onselectstart","").css('overflow',overflow);
						if (typeof(callback)=='function') callback(true);
						div_loading[id] = false;
					},
					error: function(XMLHttpRequest, textStatus, errorThrown){
						debugLog("common.loadDiv: ajax:"+issearch+" error");
						//alert('error\n XMLHttpRequest['+XMLHttpRequest+']\n textStatus['+textStatus+']\n errorThrown['+errorThrown+']');
						$("#"+id).html("<a href='' onclick='return loadSignup(data)'>REFRESH</a><br>"+XMLHttpRequest.responseText);
						$("#"+id).height('auto').removeClass('loading').attr("onselectstart","");
						if (typeof(callback)=='function') callback(false);
						div_loading[id] = false;
					}
				});
	
			});
	
	
		} else {
	
			$("#"+id).addClass('on').addClass('loading').height(height).html('');
			$("#"+id).append("<div class='oldhtml'>" + html + '</div>');
			$("#"+id).attr("onselectstart","return false;");
		
			$("#"+id+' .oldhtml').animate({
				opacity: 0.20
			}, 500, function() {
				// Animation complete.
			});
		
			$.ajax({
				url: url,
				type: "POST",
				data: data,
				cache: false,
				dataType: "html",
				success: function(data, textStatus, XMLHttpRequest){
					debugLog("common.loadDiv: ajax:"+issearch+" success");
					$("#"+id).html(data);
					$("#"+id).height('auto').removeClass('loading').attr("onselectstart","");
					if (typeof(callback)=='function') callback(true);
					div_loading[id] = false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					debugLog("common.loadDiv: ajax:"+issearch+" error");
					//alert('error\n XMLHttpRequest['+XMLHttpRequest+']\n textStatus['+textStatus+']\n errorThrown['+errorThrown+']');
					$("#"+id).html("<a href='' onclick='return loadSignup(data)'>REFRESH</a><br>"+XMLHttpRequest.responseText);
					$("#"+id).height('auto').removeClass('loading').attr("onselectstart","");
					if (typeof(callback)=='function') callback(false);
					div_loading[id] = false;
				}
			});
		
		}
	}
	return false;
}


var popup_width = 0;
var popup_title = "";
var popup_buttons = {};
var popup_id = 0;
var popup_loading = false;

function launchPopup(url,id,data) {
	debugLog("common.launchPopup('"+url+"','"+id+"') popup_loading=["+popup_loading+"]");

	if (!popup_loading) {

		popup_loading = true;

		if (!id) {
			id = popup_id++;
		
			$('body').append('<div id="popup_'+id+'" style="display:hidden"><'+'/div>');
		
			popup_width = 600;
			popup_title = "";
			popup_buttons = {};
		}
	
		if (!data) {
			data = "popup_id="+id;
		} else {
			data += "&popup_id="+id;
		}
		
		$.ajax({
			url: url,
			type: "get",
			data: data,
			cache: false,
			dataType: "html",
			success: function(data, textStatus, XMLHttpRequest){
				debugLog("common.launchPopup: ajax success");
				$('#popup_'+id).html(data).dialog({
					title: popup_title,
					modal: true,
					resizable: false,
					autoOpen: true,
					width: popup_width,
					buttons: popup_buttons,
					close: function(event, ui) {
						//alert('close');
						$('#popup_'+id).remove();
					}
				});
				popup_loading = false;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				debugLog("common.launchPopup: ajax error");
				alert('error\n XMLHttpRequest['+XMLHttpRequest+']\n textStatus['+textStatus+']\n errorThrown['+errorThrown+']');
				popup_loading = false;
			}
		});
	}
	return false;
}

/* ==================== */

function setCountry(id,provname,callback) {
	debugLog("common.setCountry('"+id+"','"+provname+"')");
	if (typeof(callback)=="undefined") callback = function(){};
	$("#"+provname).attr('disabled','disabled');
	if (id == 0) {
		$("#"+provname).html("<option value='0' selected><"+"/option>");
	} else {
		$("#"+provname).html("<option value='0' selected>Loading...<"+"/option>");
		$.ajax({
			url: "/ajax_getregions.cfm",
			type: "POST",
			data: {region_type:2, parent_id: id},
			cache: false,
			dataType: "html",
			success: function(data, textStatus, XMLHttpRequest){
				debugLog("common.setCountry: ajax success");
				if (data.length > 100) {
					data = "<option value='0' selected>Choose a State/Province<"+"/option>" + data;
				}
				$("#"+provname).html(data);
				$("#"+provname).attr('disabled','');
				callback();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				debugLog("common.setCountry: ajax error");
				alert('error\n XMLHttpRequest['+XMLHttpRequest+']\n textStatus['+textStatus+']\n errorThrown['+errorThrown+']');
				callback();
			}
		});
	}
}

function setProvince(id) {
//	alert(id);
}

var messageSet = {};

function setMessage(ids,message) {
	if (ids=='') {
		messageSet = {};
	} else {
		var id = ids.split(",");
		//if (typeof(messageSet[id[0]])=='undefined') {
			$("#message_"+id[0]+" .message").html(message);
			$("#message_"+id[0]).slideDown('fast');
			//messageSet[id[0]] = true;
		//}
		if (id.length>1) {
			//if (typeof(messageSet[id[1]])=='undefined') {
				//messageSet[id[1]] = true;
				$("input[name="+id[1]+"], select[name="+id[1]+"], textarea[name="+id[1]+"]").addClass('validate_error');
			//}
		}
	}
}

function clearMessage(ids) {
	if (ids=='') {
		messageSet = {};
	} else {
		var id = ids.split(",");
		//if (typeof(messageSet[id[0]])=='undefined') {
			$("#message_"+id[0]).slideUp('fast');
			//messageSet[id[0]] = true;
		//}
		if (id.length>1) {
			//if (typeof(messageSet[id[1]])=='undefined') {
				//messageSet[id[1]] = true;
				$("input[name="+id[1]+"], select[name="+id[1]+"], textarea[name="+id[1]+"]").removeClass('validate_error');
				$(".err[rel="+id[1]+"]").hide();
			//}
		}
	}
}

/*
"geoplugin_city":"Richmond Hill",
"geoplugin_region":"ON",
"geoplugin_areaCode":"0",
"geoplugin_dmaCode":"0",
"geoplugin_countryCode":"CA",
"geoplugin_countryName":"Canada",
"geoplugin_continentCode":"NA",
"geoplugin_latitude":"43.866699",
"geoplugin_longitude":"-79.433296",
"geoplugin_regionCode":"ON",
"geoplugin_regionName":"ON",
"geoplugin_currencyCode":"CAD",
"geoplugin_currencySymbol":"&#36;",
"geoplugin_currencyConverter":1.0056331016
*/
function getGeo(ip,callback) {
	debugLog("common.getGeo('"+ip+"')");
	// Build the URL to query
	var url = "http://www.geoplugin.net/json.gp?jsoncallback=?";
	if (ip!='') url += "&ip="+ip;
	
	// Utilize the JSONP API
	$.getJSON(url, function(data){
		debugLog("common.getGeo: getJSON");
		var geodata = {
			city: '',
			country: '',
			province: ''
		};
		try {
			geodata.city = data['geoplugin_city'];
			geodata.country = data['geoplugin_countryName'];
			geodata.province = data['geoplugin_regionName'];
		} catch(err) {}
		callback(geodata);
	});
}

/* ==================== */

function createCookie(name,value,days) {
	var expires="", date=new Date();
	if (days) {
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires="; expires="+date.toGMTString();
	}
	document.cookie=name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ=name+"=", ca=document.cookie.split(';'), c="";
	for(var i=0;i < ca.length;i++) {
		c = ca[i];
		while (c.charAt(0)==' ') c=c.substring(1,c.length);
		if (c.indexOf(nameEQ)==0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {createCookie(name,"",-1);}
