var showicons = true;
var weii = {};

weii.dateFormat = 'yyyymmdd';

$(function() {
 /*
 $('#weiipanel').weiiPanel();
 $(".WECOMPEdit").append('<span class="wecompedit">#</span>');
 $(".WEPANELEdit").append('<span class="weedit">&gt;</span>');
 $(".weedit").hover(function() {
    var pnlname = $(this).parent().attr('title');
	$(this).html('<p><b>'+pnlname+'&nbsp;panel</b></p>');	
	$('<ul class="weeditbtn"></ul>')
	.append('<li><a href="/edit.ewx?imgsrc=art&filename=_'+pnlname+'.html&new=_'+pnlname+'.html&pnl='+pnlname+'&return=index.ews">Edit Content</a></li>')
	.append('<li><a href="/design.ewx?adm=layout&cdm=6">Panel settings</a></li>')
	.appendTo(this);
 }, function() {
	$(this).text('>');	// cbdb2a
 });
 $(".wecompedit").hover(function() {
    var compinfo = String($(this).parent().attr('title')).split('|');
	var comptype = String(compinfo[0]).toLowerCase();
	$(this).html('<p><b>'+comptype+'&nbsp;component</b></p>');	
	$('<ul class="wecompeditbtn"></ul>')
	.append('<li><a href="/files.ewx?cx=12&fn='+compinfo[1]+'&ret='+wefilename+'">Settings</a></li>')
	.appendTo(this);
	switch (compinfo[0]) {
	  case "table":
		$(".wecompeditbtn").append('<li><a href="#">Table view</a></li>');
		$(".wecompeditbtn").append('<li><a href="#">Detail view</a></li>');
		$(".wecompeditbtn").append('<li><a href="#">View database</a></li>');
		$(".wecompeditbtn").append('<li><a href="#">Database Structure</a></li>');
		$(".wecompeditbtn").append('<li><a href="#">Add a record</a></li>');
		break;
	}
 }, function() {
	$(this).text('#');	// cbdb2a
 });
 */
});

/*
(function($){
    $.fn.weiiPanel = function(givenOpts) {
        opts = $.extend({
			position: 'bottom',			// panel position 'top' or 'bottom'
			height: '80px',				// set the height of the panel
			speed: 'normal',			// 'slow', 'normal', 'fast', or number in milliseconds
			moveContainer: true,		// whether to move your page container along with the panel
			container: '#webody',	// container id or class
			openBtn: '.open',			// open button id or class inside 'jqeasytrigger' div
			closeBtn: '.close',			// close button id or class inside 'jqeasytrigger' div
			openLink: '.openpanel',		// open button id or class for text links to open panel
			closeLink: '.closepanel',	// close button id or class for text links to close panel
			keepOpenCheck: '#keepopen',	// sets cookie value to show panel on load on all pages
			editLinks: '#editlinks',
			showTrigger: false,			// turn trigger tab button on/off
			showOnLoad: false			// ALWAYS open panel on page load. Ignores cookie value!	
        }, givenOpts);
		
		// refers to the selector 'weiiPanel'
		var $this = $(this);
		
		// vars needed to pass args to animate method
		var containerpadding;
		var aniOpenArgs = {};
		var aniCloseArgs = {};
		
		// add appropriate class names based on position
		if (opts.position == 'top') {
			$this.addClass('top');
			$('#jqeasytrigger').addClass('top');
			containerpadding = 'padding-top';
		} else {
			$this.addClass('bottom');
			$('#jqeasytrigger').addClass('bottom');
			$('#weiipaneloptions').css('margin-right','14px');
			containerpadding = 'padding-bottom';
		};
		
		// set panel's height
		$this.css('height', opts.height);
		
		// remove the 'px' from the height string so we can calculate the container padding
		var newpadding = opts.height.replace("px","");
		// add 25 px to the panel's height
		newpadding = parseInt(opts.height) + 25;
		
		aniOpenArgs[containerpadding] = newpadding;
		aniCloseArgs[containerpadding] = 0;

		showhidelogin();
		
		// if the cookie is set to 1 or showOnLoad is true then show the panel and the close button
		if ((readCookie('weiiPanel') == "1")||(opts.showOnLoad)) {
			if (opts.moveContainer) { $(opts.container).css(containerpadding,newpadding); };
			$this.css({'display':'block'});
			$(opts.keepOpenCheck).attr('checked', true);
		};
		
		// slide panel in and container down
            $("#we a").click(function(){
			$this.slideDown(opts.speed);
			if (opts.moveContainer) { $(opts.container).animate(aniOpenArgs, opts.speed); };
			return false;
		});	
		// slide panel out and container up
		$(".weiiclose").click(function(){
			$this.slideUp(opts.speed);
			if (opts.moveContainer) { $(opts.container).animate(aniCloseArgs, opts.speed); };
			return false;
		});

		$("#welogout").click(function() {
			weiiprivs = "";
			showhidelogin();
		});
		$("#welogin").click(function() {
			weiiprivs = "admin";
			showhidelogin();
		});
		// set cookie to show/hide edit links
		$(opts.editLinks).click(function () {
			if ($(opts.editLinks).attr('checked')) {
				//Set a cookie with the name "weiiPanel", a value of "1", until the browser session expires
				createCookie('weiiPanel','1', 0);
				$(".weedit").show();
			} else {
				//Set a cookie with the name "weiiPanel", a value of "0", until the browser session expires
				createCookie('weiiPanel','0', 0);
				$(".weedit").hide();
			};
		});
	
		// set cookie to always keep the panel open
		$(opts.keepOpenCheck).click(function () {
			if ($(opts.keepOpenCheck).attr('checked')) {
				//Set a cookie with the name "weiiPanel", a value of "1", until the browser session expires
				createCookie('weiiPanel','1', 0);
				//Check that the cookie was created using the readCookie(name) function
				//alert("You have set your weiiPanel cookie as '" +readCookie('weiiPanel')+ "'");
			} else {
				//Set a cookie with the name "weiiPanel", a value of "0", until the browser session expires
				createCookie('weiiPanel','0', 0);
				//Check that the cookie was created using the readCookie(name) function
				//alert("You have set your weiiPanel cookie as '" +readCookie('weiiPanel')+ "'");
			};
		});
		
		function createCookie(name,value,days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			} else {
				var expires = "";
			}
			document.cookie = name+"="+value+expires+"; path=/";
		}
	
		function readCookie(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var 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);
		}
	};
})(jQuery);
*/
function showhidelogin() {
		/*
		if (!weiiprivs || weiiprivs=="") {
			$("#weiipaneloptions").hide();
			$("#weloginpanel").show();
			$("#weiibtns>li").remove();
			//$("#copy").show();
		} else {
			$("#weiipaneloptions").show();
			$("#weloginpanel").hide();
			//$("#copy").hide();
			$('<li title="website"><a href="/"><img src="admin/icons/Website_48.png" alt="" />Website</a></li>').appendTo('#weiibtns');
        	$('<li title="files"><a href="/files.ewx"><img src="admin/icons/Files_48.png" alt="" />Files</a></li>').appendTo('#weiibtns');
        	$('<li title="reports"><a href="/money.ewx"><img src="admin/icons/diagram_48.png" alt="" />Reports</a></li>').appendTo('#weiibtns');
        	$('<li title="users"><a href="/users.ewx"><img src="admin/icons/Users_48.png" alt="" />Users</a></li>').appendTo('#weiibtns');
        	$('<li title="config"><a href="/admin.ewx"><img src="admin/icons/gear_48.png" alt="" />Config</a></li>').appendTo('#weiibtns');
        	$('<li title="design"><a href="/design.ewx"><img src="admin/icons/pencil_48.png" alt="" />Design</a></li>').appendTo('#weiibtns');
        	$('<li title="crm"><a href="/biz.ewx"><img src="admin/icons/CRM_48.png" alt="" />CRM</a></li>').appendTo('#weiibtns');
        	$('<li title="help"><a href="/help.ewx"><img src="admin/icons/Help_48.png" alt="" />Help</a></li>').appendTo('#weiibtns');
			
			
			$("#weiibtns>li").hover(function(e) {
				// Hover over code
				var offset = $(this).offset();
				var createpopmenu = false;
				if ($('.webarpopup').length==0) {
					createpopmenu = true;
				} else {
					if ($('.webarpopup').data != $(this).attr('title')) {
						$('.webarpopup').remove();
						createpopmenu = true;
					};
				};
				
				if (createpopmenu) {
					$('<p class="webarpopup"></p>')
					 .html('Loading ...')
					 .appendTo('body')
					 .css('top', (offset.top-200-55-$(document).scrollTop())+'px') //(e.pageY + 10 - 200) + 'px')
					 .css('left', (offset.left-60)+'px') //(e.pageX - 10) + 'px')
					 .fadeIn('fast')
					 .load('/admin/weii_'+$(this).attr('title')+'.html?2', function(data, status, response) { //);
						// Post-processing time!
						var h=$(".webarpopup").html();
						h = h.replace(/_wefilename_/g,wefilename);
						$(".webarpopup").html(h);
					});					 
					$('.webarpopup').data = $(this).attr('title'); 
					$('.webarpopup').mousemove(function(ex) {
						$("#copy").text(ex.pageX+":"+ex.pageY);
					});
					$('.webarpopup').bind( 'clickoutside', function(ex){
						$('.webarpopup').remove();
						//$("#copy").text("Outside: "+ex.pageX+":"+ex.pageY);
					});
				};
			}, function() {
				// Hover out code
				//$('.webarpopup').remove();
			}).mousemove(function(e) {
				// Mouse move code
				//$('.webarpopup')
				// .css('top', (e.pageY + 10 - 200) + 'px')
				// .css('left', (e.pageX - 10) + 'px');
				//$("#copy").text(e.pageX+":"+e.pageY);
			});			 
		}
		*/
}

weii.OpenSQL = function (sqldata,onSuccess,onError,get) {
	sqldata.src = 200;
	sqldata.JSON = 1;
	//sqldata.noext = "1";
	weii.getData("/fl.ewx",sqldata,onSuccess,onError,get);
};

weii.getData = function (url,sqldata,onSuccess,onError,get) {
	/*
		sql:
		extfields:
		from:
		max:
	*/
	var extfields = [];
	if (sqldata.extfields) {
		extfields = sqldata.extfields.split(",");
	}
	
	var method = "POST";
	if (get) method = "GET";
	$.ajax({
		type:		method,
		url: 		url, //"/fl.ewx",
		data: 		sqldata,
		dataType:	"json",
		error:		function (e) {
			if (onError) {
				onError("HTTPERR",e);
			} else {
				//alert("HTTP ERROR");
				//var results = eval(e.responseText);
				//alert(result.length);
			}
		},
		success:	function (data) {
			if (data.results.length==1 && data.results[0].result) {
				if (onError && $.isFunction(onError)) {
					onError("DBERR",data.results[0]);
				} else {
					//weii.showme(sqldata);
				}
			} else 
			if (onSuccess && $.isFunction(onSuccess)) {
				// if an extfields, process rejoin on all records!
				if (extfields.length>0) {
					for (recno=0;recno<data.results.length;recno++) {
						var rec = data.results[recno];
						for (ef=0;ef<extfields.length;ef++) {
							if (rec[extfields[ef]+"extc"]) {
								if (rec[extfields[ef]+"extc"]) {
									var ec = eval(rec[extfields[ef]+"extc"]);
									for (i=1;i<=ec;i++) {
										rec[extfields[ef]] += rec[extfields[ef]+"ext"+i];
									}
								}
							}
						}
					}
				}
				onSuccess(data.results);
			}
		}
	});
	
}

weii.ExecSQL = function (sqldata,onSuccess,onError,get) {
	sqldata.src = 201;
	sqldata.JSON = 1;
	var method = "POST";
	if (get) method = "GET";
	
	$.ajax({
		type:		method,
		url: 		"/fl.ewx",
		data: 		sqldata,
		dataType:	"json",
		error:		function (e) {
			if (onError && $.isFunction(onError)) {
				onError("HTTPERR",e);
			}
		},
		success:	function (data) {
			if (data.results.length==1) {
				if (data.results[0].result=="OK") {
					if(onSuccess && $.isFunction(onSuccess)) {
						onSuccess(data.results[0]);
					}
				} else {
					if (onError && $.isFunction(onError)) {
						onError("DBERR",data.results[0]);
					}
				}
			} else 
			if (onError && $.isFunction(onError)) {
				onError("DBERR",{result:""});
			}
		}
	});
	
}

weii.loadScript = function (url,onSuccess) {
		$.ajax({ 
		  url: url, 
		  dataType: 'script', 
		  success: function() { 
			if (onSuccess && $.isFunction(onSuccess)) onSuccess();
		  } 
		}); 
}		

weii.loadRSS = function (reqdata,onSuccess,onError) {

	reqdata.src = 56;
	
	$.ajax({ 
		type:	"get",
		url: "/fl.ewx", 
		data: reqdata,
		dataType: 'xml', 
		error:	function (e) {
			if (onError && $.isFunction(onError)) onError(e);
		},
		success: function(data) { 
			if (onSuccess && $.isFunction(onSuccess)) onSuccess(data);
		} 
	}); 
}

weii.logout = function (onLoggedOut) {
	var senddata = {};
	senddata.src = 510;
	senddata._welogout = "now";
	senddata.JSON = 1;
	$.post("/fl.ewx", senddata , function(data) { 
		if (data.results.length>0) {
			var res = data.results[0];
			_weid = res.sessionid;
			_userid = res.userid;
			if (onLoggedOut && $.isFunction(onLoggedOut)) onLoggedOut(res);

		} else {
			if (onLoggedOut && $.isFunction(onLoggedOut)) onLoggedOut({});
		}
	});
}

weii.attemptLogin = function (un,pw,onSuccess,onFailure) {
	var senddata = {};
	senddata.src = 510;
	senddata._qlu = un;
	senddata._qlp = pw;
	senddata.JSON = 1;
	$.post("/fl.ewx", senddata , function(data) { 
			if (data.results.length>0) {
				var res = data.results[0];
				_weid = res.sessionid;
				_userid = res.userid;
				if (onSuccess && $.isFunction(onSuccess)) onSuccess(res);
			} else {
				if (onFailure && $.isFunction(onFailure)) onFailure();
			}
	});
}

weii.dbdate = function (dt) {
	// yyyymmdd (optionally hhnnss)
	var result = "";
	dt = String(dt);
	while (dt.length<8) { dt += '01'; };
	switch (weii.dateFormat) {
		default:
			result = dt.substr(6,2)+'/'+dt.substr(4,2)+'/'+dt.substr(2,2);
			break;
	}
	return result;
}

weii.datetodb = function (d) {
	var result = ''+d.getDate();
	if (result.length<2) result = '0'+result;
	result = (d.getMonth()+1)+result;
	if (result.length<4) result = '0'+result;
	result = d.getFullYear()+result;
	return result;
}

weii.pad0 = function (v,width) {
	v = ''+v;
	if (!width) { width = 2; }
	while (v.length<width) { v = '0'+v; }
	return v;
}

weii.IsValidEmail = function (email) {
	var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	return filter.test(email);
}

weii.scrollTo = function (item,pad) {
	item.show();
	var offset = item.offset();
	var targetOffset = offset.top-pad;
	$('html,body').animate({scrollTop: targetOffset }, 500);
};

weii.showme = function (obj) {
	var s = "";
	for (v in obj) {
		s += v+": "+obj[v]+" * ";
	}
	alert(s);
}

weii.sendemail = function (address,from,subject,msg,pw,onComplete) {
	var email = {};
	email.src = 55;
	email.tg = pw;// "wblnday";
	email.to = address;
	email.from = from; //"info@whiteballoonday.com.au";
	email.fname = from; //"White Balloon Day";
	email.subject = subject; //"7 September is White Balloon Day";
	email.msg = msg;

	email.JSON = 1;
	
	$.ajax({ 
		type:	"POST",
		url: "/fl.ewx", 
		data: email,
		success: function(data) { 
			var rec = data.results[0];				
			//if (rec.result == "ok") {
			//}
			if (onComplete && $.isFunction(onComplete)) onComplete(rec);
		}, 
		error:	function (e) {
			if (onComplete && $.isFunction(onComplete)) onComplete({result:'err',e:e},e);
		}
	}); 
}

