/* javascript library */
function sortUpdate( index ){
	if( _snap_timer_ ) clearTimeout( _snap_timer_ );
	_snap_timer_ = setTimeout("snapshot()", 2000);
};

// webnote:item
function webnote_n() {
	this.id = 0;
	this.edit = false;
}
webnote_n.prototype.init = function( id ){
	this.id = id;
	webnote.init( id );
}
// webnote:main
webnote = {
	show:function( id ){
		var target = $("#webnote_body_" + id );
		target.html( lang.loading );
		var success = function( reply ){
			target.html( webnote.prepare( id, reply ) ); 
		};
		$.ajax({
			type: "POST",
			dataType:"json",
			url: conf.base_url,
			data: { m:id },
			success: success,
			async: conf.async,
			global: false
		});
	},
	write:function( id ){
		var o = eval("webnote_"+id);
		if( o.edit ) return;
		o.edit = true;
		var obj = $("#wn_" + id );
		var data = $("#wn_"+id).html();
		data = htmlToText( data.replace(/\r\n/g," ") );
		var obj2 = _gel("wn_" + id );
		var oWidth = obj2.offsetWidth;
		var oHeight = (obj2.offsetHeight>100) ? obj2.offsetHeight : 100;
		var frm = "<textarea id='bntxt_" + id +"' style='width:"+oWidth+"px;height:"+oHeight+"px;border:1px dashed #ff0000;font-size:10px;font-family:Verdana,Arial;' onblur='webnote.save("+id+");return false;' onmouseover='this.focus(); return false;'>" + data + "</textarea>";
		obj.html(frm);
	},
	save:function( id ){
		var o = eval("webnote_"+id);
		var obj = $("#bntxt_"+id );
		var txt = obj.attr('value');
		if (txt=='undefined') txt='';
		var data = core.text2html(txt);
		o.edit = false;
		var url = conf.base_url;
		var obj = { m: id, a:"change", note_text: data };
		var success = function( reply ){
			var web = eval("webnote_"+id );
			web = reply;
			$("#webnote_body_" + id ).html( webnote.prepare( id, reply ) ); 
		}
		$.post( url, obj, success, "json" );
	},
	prepare:function(id, data ){
		var html = '';
		var data = data.text;
		html += '<table cellpadding="5" cellspacing="5" border="0" width="100%">'
		html += '<tr><td onclick="javascript:webnote.write('+id+');" id="wn_'+id+'">';
		html += data ; 
		html += '</td></tr></table>';
		return html;
	},
	init:function( id ){
		$("#settings_" + id).submit( function() {
			var div =  "#settings_" + id;
			var label = $(div+" :input").fieldValue()[0];
			var url = conf.base_url;
			var obj = { m: id , a:'settings',l: label };
			var success = function(){
				core.setTitle( id, label );
				$(div).parents("li.first").parent("ul").hide();
			}
			$.post( url, obj, success );
			return false;
		});
		webnote.show( id );
	}
};
// rss_data:item
rss_data_n = function(){
	this.mode = 0;
	this.show = function( id ){
		//rss_data.show( id );
	};
	this.init = function( id ){
		rss_data.init( id );
	}
}
// rss_data
var rss_data = {
	prepare:function( id, data ){
		var html = '';
		if( data.results != null && data.results != 'undefined'){
			var results = data.results;
			var len = results.length;
			for(i=0;i<len;i++){
				obj = results[i];
				html += '<blockquote class="media_item_1 clearfix last">';
				html += '<a class="thumb" href="'+ obj.link+'" target="_blank">';
				html += '<img src="'+obj.image+'" />';
				html += '</a>';
				html += '<div class="description">';
				if(obj.user_id != null && obj.user_id != 'undefined'){
					html += '<h4><a href="javascript:remove_bookmark('+id+','+ obj.user_id +','+obj.id+');">remove</a></h4>';
				}
				
				html += '<h3><a href="'+obj.link+'" target="_blank">'+ obj.title+'</a></h3>';
				if(obj.description != null){
					html += '<p>';
					html += obj.description;
					html += '</p>';
				}
				html += '</div>';
				html += '<ul class="stats">';
				html += '<li class="date">'+ obj.date_added+'</li>';
				html += '<li class="hits">'+ obj.num_views+'</li>';
				html += '<li class="rating">'+obj.average_rate+ '</li>';
				html += '</ul>';
				html += '</blockquote>';
			}
			if( data.count > 0){
				pg_div = 'rss_pager_'+ id;
				html += '<div id="' + pg_div + '" class="pager">';
				html += __pager(id, data);
				html += '</div>';
			}
		}else{
			html += '<div class="unread_mail"><p>No Items</p></div>';
		}
		return html;
	},
	processJsonRSS:function( id, data ){
		$( "#rss_search_result_" + id ).html( 'op' );//rss_data.result_RSS( id, data ) );
	},
	init:function( id ){
		var o = eval("rss_data_"+id);
		if( o.mode != 1 ){
			var success = function( reply ){
				data = $.parseJSON( reply );
				rss_data.show( id );
				//rss_data.processJsonRSS( id, data );
			};
			$.post( conf.base_url, { p:1, m:id }, success ); 
		}else{
			var opt = {
				dataType:'json',
				url: conf.base_url,
				success: function( reply ){
					rss_data.show( id );
					//rss_data.processJsonRSS( id, reply );
				}
			}
			$( "#rssForm_" + id ).ajaxForm( opt );
		}
		// settings
		$("#settings_"+id).submit( function() {
			var div = "#settings_" + id;
			var label = $(div+" :input").fieldValue()[0];
			var rows =  $(div+" :input").fieldValue()[1];
			$.post( conf.base_url, { m: id, a:'settings',l: label, r: rows }, function(data){
					core.setTitle( id, label);
					$(div).parents("li.first").parent("ul").hide();
				}
			);
			rss_data.show( id );
			return false;
		});
		rss_data.show( id );
	},
	show:function( id ){
		var target = $( "#rss_search_result_" + id );
		target.html( lang.loading );
		var module = $("#module_"+id);
		var success = function( reply ) {
			target.html( rss_data.prepare( id, reply ) );
		};
		$.ajax({
			type: "POST",
			dataType: "json",
			url: conf.base_url,
			data: {m:id,a:'show'},
			success: success,
			async: conf.async,
			global: false
		});
	}
}

// rendering
function new_pager(id, page, target){
	var success = function( reply ){
		$('#' + target + id ).html( rss_data.prepare( id, reply ) );
	};
	$.ajax({
		type: "POST",
		dataType: "json",
		url: conf.base_url,
		data: {m:id,p:page,a:'pager'},
		success: success,
		async: conf.async
		});
}
// rendering
function new_gmail_pager(id, page, target){
	var success = function( reply ){
			reply = $.secureEvalJSON( reply );
			google_m.processJson( id, reply );	
	};
		$.ajax({
			type: "POST",
			url: conf.base_url,
			data: {m:id, p:page, a:'show'},
			success: success,
			async: conf.async,
			global: false
		});
}
// rendering
function new_hotmail_pager(id, page, target){
		$("#" + target + id ).html("<p>Loading...</p>");
		var success = function( reply ){
			hotmail_m.processJson( id, reply );
		}
		$.ajax({
			type: "POST",
			url: conf.base_url,
			data: {m:id, p:page, a:'show'},
			success: success,
			async: conf.async,
			global: false,
			dataType:"json"
		});
}
// rendering
function new_yahoo_pager(id, page, target){
		$("#" + target + id ).html( lang.loading );
		var success = function( data ){
			yahoo_m.processJson( id, data );
		}
		$.ajax({
			type: "POST",
			url: conf.base_url,
			data: {m:id, p:page, a:'show'},
			success: success,
			async: conf.async,
			global: false,
			dataType:"json"
		});
}
function __pager(m_id, data){
	var html = '';
	var link = 'javascript:pager' + m_id;
	var pager = data.pager;
	if(pager == null || pager == 'undefined'){
		return html;
	}
	var first = pager.first;
	var next = pager.next;
	var prev = pager.prev;
	var last = pager.last;
	var current = pager.current;
	var pages = pager.pages;
	html += '<ul class="clearfix">';
	html += '<li><a href="'+link +'('+ first+');" title="first">&laquo;</a></li>';
	if(prev){
		html += '<li><a href="'+link +'('+ prev+');" title="prev">&lsaquo;</a></li>';
	}
	var len = pages.length;
	for(i=0;i<len;i++){
		if(pages[i] == current){
			html += '<li class="selected"><span>'+pages[i]+'</span></li>';
		}else{
			html += '<li><a href="'+link +'('+ pages[i]+');" title="'+pages[i]+'">'+ pages[i]+'</a></li>';
		}
	}
	if(next){
		html += '<li><a href="'+link +'('+ next+');" title="next">&rsaquo;</a></li>';
	}
	html += '<li class="last"><a href="'+link +'('+ last+');" title="last">&raquo;</a></li>';
	html += '</ul>';
	return html;
}
function remove_bookmark(module_id, user_id, item_id){
	$.post(conf.base_url, {m:module_id,a:'remove',i_id:item_id}, function(data){
		var fn = "_show"+module_id;
		eval(fn+"()");
	});
}
function result_RSS(id, data){
	return rss_data.prepare( id, data );
}
function result_Weather( data ){
	return weather.prepare( data );
}
// google
function result_Google(id, data) 
{
	var html = '';
	if( data.results != undefined )
	{
		var results = data.results;
		var len 	= data.results.length;
		if( len == 0 ) {
			html += "<div class='unread_mail'>";
			html += "<p>Your search - <strong>" + data.q + "</strong> - did not match any documents.</p>";
			html += "<p>Suggestions:</p>";
			html += "<ul>";
			html += "<li>* Make sure all words are spelled correctly.</li>";
			html += "<li>* Try different keywords.</li>";
			html += "<li>* Try more general keywords.</li>";
			html += "</ul>";
			html += "</div>";
		}
		for(i=0;i<len;i++)
		{
			obj = results[i];
			html += '<blockquote class="media_item_2">';
			html += '<h3><a href="'+obj.url+'" target="_blank">'+ obj.title+'</a></h3>';
			html += '<div class="description">';
			html += '<p>';
			html += obj.content;
			//html += obj.snippet;
			html += '</p>';
			//html += '<strong><a href="http://'+ obj.site+'">'+obj.displayUrl+'</a></strong>';
			html += '<strong><a href="'+ obj.unescapedUrl+'">'+obj.visibleUrl+'</a></strong>';
			html += '</div>';
			html += '</blockquote>';  
		}
	}else{
		html += "<div class='unread_mail'><p>No results found!</p></div>";
	}
	if(data.pager != null)
	{
		pg_div = 'google_pager_'+ id;
		html += '<div id="' + pg_div + '" class="pager">';
		html += __pager(id, data);
		html += '</div>';
	}
	return html;
}
// common 
function textToHtml( str ) { return core.text2html( str ); }
function htmlToText( str ){ return core.html2text(str); }
function result_Webnote( id, data ) { webnote.prepare( id, data ); }
function findTaskById(m_id, t_id) { return task.findTaskById( m_id, t_id ); }
function edit_task_row( id, obj) {
	var html2 = '';  
	var obj2 = _gel( "c_" + id );
	var oWidth = obj2.offsetWidth - 30;
	var style = 'style="width:'+oWidth+'px;height:12px; border:1px dashed #101010;font-size:10px;font-family:Verdana,Arial;"'; 
	html2 += '<td>&nbsp';
	val = fixIt(obj.text)
	html2 += '<input name="n_task'+obj.id+'" id="n_task'+obj.id+'" type="text" maxlength="50" size="20" value="'+val+'" '+ style +' onblur="save_'+id+'('+ obj.id+');return false;"/>';   
	html2 += '<td width="16" align="right"><a href="javascript:save_'+id+'('+ obj.id+');"><img src="/modules/tasks/img/edit.gif" align="absmiddle" /></a></td>';
	html2 += '<td width="16" align="right"><a href="delete_'+id+'('+ obj.id+');"><img src="/modules/tasks/img/deleteLink.gif" align="absmiddle" /></a></td>';
	return html2;
}

function _gel( id ){
	return document.getElementById ? ( document.getElementById(id) ? document.getElementById(id) : null ) : document.all[id];
}

function fixIt(x){
	x = x.replace(/'/g,'&apos;');
	x = x.replace(/"/g,'&quot;');
	return x;
}

function task_row(m_id,obj){ return task.task_row( id, obj ); }
function result_Tasks( id, data){ return task.prepare( id, data ); }

function result_Shared(m_id, jsondata){
	var html = '';
	if(jsondata.results != null && jsondata.results != 'undefined')
	{
		var results = jsondata.results;
		var len = results.length;
		for(i=0;i<len;i++)
		{
			obj = results[i];
			html += '<blockquote class="media_item_2">';
			html += '<a href="index.php?v_uid='+obj.u_id+'&username='+obj.username+'" target="_top">Page of <b>'+ obj.username+'</b></a>';
			html += '</blockquote>';
		}
		if(jsondata.count > 0)
		{
			pg_div = 'rss_pager_'+ m_id;
			html += '<div id="' + pg_div + '" class="pager">';
			html += __pager(m_id, jsondata);
			html += '</div>'
		} 
	}
	return html;
}
var PLEASE_CLICK="Please click on settings to set up your email account";
function result_hotmail(jsondata) 
{
	var html = '';
	html += '<div class="unread_mail">';
	html += '<p><img class="favicon" src="/img/icon_hotmail.gif" /> You have '+ jsondata.unread+' unreaded mails</p>';	
	html += '</div>';
	
	html += '<div class="last_mail">'; 
	var len = jsondata.items.length;
	for(i=0;i<len;i++)
	{
		obj = jsondata.items[i];
		html += '<blockquote class="media_item_3">';
		html += '<h3><a href="'+obj.url+'" target="_blank"><strong>'+ obj.subject +'</a></h3>';
		html += '<p class="description">SENDER: '+ obj.sender +'</p>';
		html += '</blockquote>';
	}
	html += '</div>';
	return html;
}

// end of rendering
function hideMenu(){
	$("td#site_frame_left").toggle();
	$("#wrapper").toggleClass("opened");
}

function EscapeQuote(str)
{
	var ret = ''
	for(i=0;i<str.length;i++)
	{
		ch = str[i];
		if(ch=='\'') {
			ret = ret + '\\' + '\'';
		}
		else if(ch == '\"'){
			ret = ret + '\\' + '\"';
		} else {
			ret = ret + ch;
		}
	}
	return ret;
}

var title = '{/literal}{$title|escape}{literal}';
function title_save(){
	var val= $("#title_edit").attr('value');
	$.post( conf.base_url,{module:'user',action:'title','title': val});
	conf.page.title = val; //title = val;
	var htm = '<span onclick="javascript:title_edit();return false">'+val+'</span>'
	$('#title').html(htm);
}

function title_edit(){
	zz = fixIt(conf.page.title);
	var htm = '<input id="title_edit" onblur="title_save()" style="width:300px;height:20px; border:1px dashed #ffffff;font-size:18px;FONT-FAMILY:Verdana,Arial;" maxlength="50" size="20" value="'+zz+'"/>';
	$('#title').html(htm);
	$('#title_edit').focus();
}
	
	// fix of autor of JQUERY TABS
	// http://groups.google.com/group/jquery-en/browse_thread/thread/522ccd10970782e5/95fd2de963ed4266?lnk=gst&q=jquery+tabs&rnum=1#95fd2de963ed4266
	jQuery.fn.newTabs = function(options) 
	{
		$("ul.tabs-nav a", this).unbind('click');
		return this.tabs(options);
	}

	// GEOMETRY
	function newTab()
	{
		var cnt = $('#page_tabs').children("ul.page_tabs").children().size();
		$.post(
			conf.base_url,
			{g:2, c:cnt},
			function (data) {
				//jsondata = $.parseJSON(data);
				html = '<li><a href="#tab_'+data.idx +'" title="'+data.name+'" info="'+data.id+'">'+data.name+'</a>  <span class="close_button">x</span></li>';
				$("#page_tabs").children("ul.page_tabs").append(html);
				
				html2 = '<div id="tab_'+ data.idx +'" class="tab_content tabs-container" info="'+data.id+'" count="0">';
				//html2 += '<div class="column" info="0" id="column_'+ cnt +'_0">&nbsp;</div>'; 
				//html2 += '<div class="column" info="1" id="column_'+ cnt +'_1">&nbsp;</div>'; 
				//html2 += '<div class="column" info="2" id="column_'+ cnt +'_2">&nbsp;</div>'; 
				//html2 += '</div>';  
				
				html2 += '<div class="column" info="0" id="column_'+ data.idx +'_0">&nbsp;</div>'; 
				html2 += '<div class="column" info="1" id="column_'+ data.idx +'_1">&nbsp;</div>'; 
				html2 += '<div class="column" info="2" id="column_'+ data.idx +'_2">&nbsp;</div>'; 
				
				$("#page_tabs").append(html2);
				$('#page_tabs').newTabs();
				$("#page_tabs > ul > li:gt(0) > span.close_button").click(function() {
					closeTabCallback($(this).prev().attr("info"));
				});
			}, "json");
	}
	
	function closeTabCallback (id) {
		if(confirm("Are you sure you want to close this tab?")){
			$.post(conf.base_url, {g:4, tab_id:id}, function (data) {
					top.location.href = conf.base_url;
				}
			);
		}
	}

	function minimizeCallback(X, Y, id){
		$.post(conf.base_url, {a:'minimize', m:id});
	}

	function closeCallback (x, y, id)
	{
		$.post(conf.base_url, {a:'delete', m:id}, function(){
				snapshot();
			}
		);
	}

	function getModuleXY(a_elem){
		module_id = a_elem.attr("info");
		column = a_elem.parents("div.column");
		module = $("#module_" + module_id);
		index = column.children("div.module").index(module[0]);  
		return new Array(column.attr("info"), index);
	}
  

	function changeColorCallback(id,color){
		$.post(conf.base_url,{a:'color',m:id,c:color});
	}
	

	function addFeed(){
		var val =$('#add_feed').children('input.text').attr('value');
		if(val != '')
		{
			// make ajax call to store feed in DB for rewiews 
			//$.post('index.php',{});  
		}
		$('#add_feed').children('input.text').attr('value','');
	}

	function newRSS(mode,f_id)
	{
		var index = $('#page_tabs').activeTab() - 1;
		var col = $("#tab_"+ index).children(":first-child");
		if(f_id != null) {
			var obj = { g: 1, t: index, name: 'rss_data', mode: mode, f_id:f_id };
		} else {
			var obj = { g: 1, t: index, name: 'rss_data', mode: mode  };
		}
		$.post( 
			conf.base_url,
			obj,
			function (data){
				jsondata = $.parseJSON(data);
				first_child = col.children(":first-child");
				if (first_child.is("div")) {
					first_child.before(jsondata.data);
				} else {
					col.append(jsondata.data);
				}
				// call module init/ document.ready
				eval(jsondata.js);
				var script = document.createElement("script");
				script.lang = 'javascript';
				script.text = jsondata.js;
				
				document.getElementsByTagName('head')[0].appendChild(script); 
				
				// JS added in DOM
				snapshot();
				var div = col.children(":first-child");
				$(".module_options li.settings a", div).click( function() {
					$(this).next("ul").toggle();
				});
				// color buttons
				$(".module_options li.color_changer a", div).click( function() {
					a = $(this);
					$.each(["orange", "yellow", "green", "blue", "red"], function(i, n){
						a.parents("div.module").removeClass(n);
					});
					$(this).parents("div.module").addClass($(this).attr("title").toLowerCase());
					$(this).parents("li.color_changer:first").parent("ul").hide();
				});
				
				// minimize button
				$(".module_options li.minimize a", div).click( function() {
					$(this).parents("div.module_head:first").siblings("div.module_body").toggle(500);
				});
				
				// close button
				$(".module_options li.close a", div).click( function() {
					var state = confirm("Are you sure you want to remove this module?");
					if( state ){
						coord = getModuleXY($(this));
						module_id = $(this).attr("info");
						closeCallback(coord[0], coord[1], module_id);
						module = $("#module_" + module_id).remove();
					};
				});
				
				// refresh button
				$(".module_options li.refresh a", div).click( function() {
					module_id = $(this).attr("info");
					module = $("#module_" + module_id);
					var fn = "_show"+module_id;
					eval(fn+"()");
				});
				
				// move buttons  
				$(".module_options li.move a", div).click( function() {
					if ($(this).is(".func_button")){
						$(this).next("ul").toggle();
					} else {
						module_id = $(this).attr("info");
						current_column = $(this).parents("div.column");
						current_module = $("#module_" + module_id);
						X = parseInt(current_column.children("div.module").index(current_module[0]));
						Y = parseInt(current_column.attr("info"));
						action = $(this).attr("title").toLowerCase();
						switch (action) {
      
                case "up" : 
                  if (X != 0) {
                    current_column.children().eq(X - 1).before(current_module);
                    snapshot();
                  };
                  break;
      
                case "down" :
                  current_childs = current_column.children();
                  if (X != current_childs.size() - 1) {
                    current_childs.eq(X + 1).after(current_module); 
                    snapshot();
                  };
                  break;
      
                case "left" :
                  if (Y > 0) {
                    tab_num = $('#page_tabs').activeTab() - 1;
                    left_column = $("#column_" + tab_num + "_" + (parseInt(Y) - 1));
                    left_childs = left_column.children();
                    left_childs_cnt = left_childs.size();
                    if (left_childs_cnt > 0) {
                      new_index = X <= (left_childs_cnt - 1) ? X : left_childs_cnt;
                      if (new_index > 0) {
                        left_childs.eq(new_index - 1).after(current_column.children().eq(X));
                      } else {
                        left_childs.eq(new_index).before(current_column.children().eq(X));
                      }
                    } else {
                      left_column.append(current_column.children().eq(X));
                    }
                    snapshot();
                  };
                  break;
              
                case "right" :    
                   if (Y < 3) {
                    tab_num = $('#page_tabs').activeTab() - 1;
                    right_column = $("#column_" + tab_num + "_" + (parseInt(Y) + 1));
                    right_childs = right_column.children();
                    right_childs_cnt = right_childs.size();
                    if (right_childs_cnt > 0) {
                      new_index = X <= (right_childs_cnt - 1) ? X : right_childs_cnt;
                      if (new_index > 0) {
                        right_childs.eq(new_index - 1).after(current_column.children().eq(X));
                      } else {
                        right_childs.eq(new_index).before(current_column.children().eq(X));
                      }
                    } else {
                      right_column.append(current_column.children().eq(X));
                    }
                    snapshot();
                   }
                   break;
              }      
              $(this).parents("ul:first").toggle();
      
              return false; 
          }
        });

      }
    );     
}


function newModule (name) {
	var index = $('#page_tabs').activeTab() - 1;
	var col = $("#tab_"+ index).children(":first-child");
	$.post(
		conf.base_url,
		{g:1, t:index, name:name},
		function (data) {
			jsondata = $.parseJSON(data);
			first_child = col.children(":first-child");
			if (first_child.is("div")) {
				first_child.before(jsondata.data);
			} else {
				col.append(jsondata.data);
			}
			eval(jsondata.js);
			var script = document.createElement("script");
			script.lang = 'javascript';
			script.text = jsondata.js;
			document.getElementsByTagName('head')[0].appendChild(script); 
			// JS added in dom
			snapshot();
			var div = col.children(":first-child"); 
			$(".module_options li.settings a", div).click( function() {
				$(this).next("ul").toggle();
			});

			// color buttons
			$(".module_options li.color_changer a", div).click( function() {
				a = $(this);
				$.each(["orange", "yellow", "green", "blue", "red"], function(i, n){
					a.parents("div.module").removeClass(n);
				});
				newcolor = $(this).attr("title").toLowerCase();
				$(this).parents("div.module").addClass(newcolor);
				$(this).parents("li.color_changer:first").parent("ul").hide();
				changeColorCallback($(this).attr("info"), newcolor);
			});

			// minimize button
			$(".module_options li.minimize a", div).click( function() {
				$(this).parents("div.module_head:first").siblings("div.module_body").toggle();
			});

			// close button
			$(".module_options li.close a", div).click( function() {
				var state = confirm("Are you sure you want to remove this module?");
				if( state ){
					id = $(this).attr("info");
					coord = getModuleXY( $(this) );
					closeCallback(coord[0], coord[1], id);
					module = $("#module_" + id).remove();
				}
			});

			// refresh button
			$(".module_options li.refresh a", div).click( function() {
				module_id = $(this).attr("info");
				module = $("#module_" + module_id);
				var fn = "_show" + module_id;
				eval(fn+"()");
			});

			//over
			$('div.module_options li.drag_and_drop a').unbind("mousedown");
			$('div.module_options li.drag_and_drop a').bind("mousedown", function(){
				sortable_enable();
			});

			//out
			$('div.module_options li.drag_and_drop a').unbind("mouseup");
			$('div.module_options li.drag_and_drop a').bind("mouseup", function(){
				sortable_disable();
			});

			// move buttons
			$('div.module_options li.move a', div).unbind("mousedown");
			$('div.module_options li.move a', div).bind("mousedown", function(){
				sortable_enable();
			});
			
			$('div.module_options li.move a', div).unbind("mouseup");
			$('div.module_options li.move a', div).bind("mouseup", function(){
				sortable_disable();
			});
			
			
		$(".module_options li.move a", div).click( function() {
			if ($(this).is(".func_button")) {
				$(this).next("ul").toggle();
			} else {
				module_id = $(this).attr("info");
				current_column = $(this).parents("div.column");
				current_module = $("#module_" + module_id);
				X = parseInt(current_column.children("div.module").index(current_module[0]));
				Y = parseInt(current_column.attr("info"));
				action = $(this).attr("title").toLowerCase();
				switch (action) {
					case "up" : 
					if (X != 0) {
						current_column.children().eq(X - 1).before(current_module);
						snapshot();
					};
					break;
					case "down" :
					current_childs = current_column.children();
					if (X != current_childs.size() - 1) {
						current_childs.eq(X + 1).after(current_module); 
						snapshot();
					};
					break;
					case "left" :
					if (Y > 0) {
						tab_num = $('#page_tabs').activeTab() - 1;
						left_column = $("#column_" + tab_num + "_" + (parseInt(Y) - 1));
						left_childs = left_column.children();
						left_childs_cnt = left_childs.size();
						if (left_childs_cnt > 0) {
							new_index = X <= (left_childs_cnt - 1) ? X : left_childs_cnt;
							if (new_index > 0) {
								left_childs.eq(new_index - 1).after(current_column.children().eq(X));
							} else {
								left_childs.eq(new_index).before(current_column.children().eq(X));
							}
						} else {
							left_column.append(current_column.children().eq(X));
						}
						snapshot();
					};
					break;
					case "right" :    
					if (Y < 3) {
						tab_num = $('#page_tabs').activeTab() - 1;
						right_column = $("#column_" + tab_num + "_" + (parseInt(Y) + 1));
						right_childs = right_column.children();
						right_childs_cnt = right_childs.size();
						if (right_childs_cnt > 0) {
						new_index = X <= (right_childs_cnt - 1) ? X : right_childs_cnt;
						if (new_index > 0) {
							right_childs.eq(new_index - 1).after(current_column.children().eq(X));
						} else {
							right_childs.eq(new_index).before(current_column.children().eq(X));
						}
						} else {
						right_column.append(current_column.children().eq(X));
						}
						snapshot();
					}
					break;
					}
				$(this).parents("ul:first").toggle();
				return false; 
			}
			});
	});

}

	// snapshot on current tab
	function snapshot(){
		var s0,s1,s2;
		var tab_num = $('#page_tabs').activeTab() - 1;
		var items = [];
		var unique = {};
		// 0
		var c0 = $("#column_" + tab_num + "_0");
		var i0 = c0.children().size();
		for(i=0;i<i0;i++){
			var m = c0.children().eq(i);
			var id = $(m).attr('info');
			if( unique[ id ] == undefined ) {
				unique[ id ] = 1;
				items.push( id );
			}
		}
		s0 = items.join(':');
		items = [];
		// 1 
		var c1 = $("#column_" + tab_num + "_1");
		var i1 = c1.children().size();
		for(i=0;i<i1;i++){
			var m = c1.children().eq(i);
			var id = $(m).attr('info');
			if( unique[ id ] == undefined ) {
				unique[ id ] = 1;
				items.push( id );
			}
		}
		s1 = items.join(':');
		
		// 2
		items = [];
		var c2 = $("#column_" + tab_num + "_2");
		var i2 = c2.children().size();
		for(i=0;i<i2;i++){
			var m = c2.children().eq(i);
			var id = $(m).attr('info');
			if( unique[ id ] == undefined ) {
				unique[ id ] = 1;
				items.push( id );
			}
		}
		s2 = items.join(':');
		var success = function(){
		};
		$.ajax(
		{
			type: "POST",
			url: conf.base_url,
			data: { g: 0, t:tab_num, c0: s0, c1: s1, c2: s2 },
			async: conf.async,
			global: false,
			success: success
		});
	}
	// marian work, break your neck
	function _show(id){
		rss_data.show( id );
	}

	core = {
		setTitle:function( id, title ){
			$("#module_" + id + " .module_head > h2").text( core.text2html( title ) );
		},
		text2html:function( str ){
			var IE = (document.all) ? 1 : 0;
			str = str.replace(/\&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/  /g,"&nbsp; ").replace(/\r/g,"");
			str = (IE) ? str.replace(/\n/g,"<BR>") : str.replace(/\n/g,"<br>");
			return str;
		},
		html2text:function( str ){
			return str.replace(/\&amp;/g,"&").replace(/\&lt;/g,"<").replace(/&gt;/g,">").replace(/\&nbsp;/g," ").replace(/<BR>/g,"\r\n").replace(/<br>/g,"\r\n");
		}
	}
	
	// old functions
	function setTitle( id, title ){ core.setTitle( id, title ); };

 //add IE6 fix form appear on the top
function iFelement(ul_offset, ul_height, num_in_arr)
{
	this.unid = "iframeelid_" + num_in_arr;
	this.pleft = ul_offset.left;
	this.ptop = ul_offset.top;
	this.dwidth = 200
	this.dheight = ul_height;
	this.htmlcd = '<iframe style="border-style:none; position:absolute; z-index:998; left:' + this.pleft + 'px; top:' + this.ptop + 'px; height: ' + this.dheight + 'px; width: ' + this.dwidth + 'px; " id="' + this.unid + '" src="" frameborder="0"></iframe>';
	window.alert(this.htmlcd);
}
 //add IE6 fix form appear on the top
 function iFelementsObj(){
	this.iFelement_arr = new Array();
	this.lastIndex = 0;
	this.FindIFElement = function(ul_offset, ul_height){
		var id_finded = -1;
		for(cix in this.iFelement_arr) { //cix = 0; cix<this.iFelement_arr.length; cix++){
			if(this.iFelement_arr[cix].pleft == ul_offset.left && this.iFelement_arr[cix].ptop == ul_offset.top && this.iFelement_arr[cix].dheight == ul_height) {
				id_finded = cix; break;
			}
		}
		return id_finded;
	}
	this.AddIFElement = function(ul_offset, ul_height) {
		var isSameIFElement = this.FindIFElement(ul_offset, ul_height);
		if(isSameIFElement < 0){
			this.iFelement_arr[this.lastIndex] = new iFelement(ul_offset, ul_height, this.lastIndex);
			this.lastIndex++;
window.alert("added=" + (this.lastIndex-1));
		} else {
window.alert("id find =" + isSameIFElement);
		}
	}
	this.RemoveIFElement = function(IFEindex){
		//this.iFelement_arr[this.iFelement_arr.length].RemoveIFEfromdoc();
		window.alert("lastIndex1 =" + this.lastIndex);
		delete this.iFelement_arr[IFEindex];
		if (IFEindex == this.lastIndex - 1) {
			this.lastIndex--;
		}
window.alert("lastIndex2 =" + this.lastIndex);
	}
	this.ToggleIFElement = function(ul_offset, ul_height, ul_offset_before, ul_height_before){
		if(ul_offset_before.left == 0 && ul_offset_before.top == 0) {
			this.AddIFElement(ul_offset, ul_height);
			//this.iFelement_arr[this.lastIndex] = new iFelement(ul_offset, ul_height, this.lastIndex);
			//this.lastIndex++;
		} else {
			var isSameIFElement = this.FindIFElement(ul_offset_before, ul_height_before);
			if (isSameIFElement >= 0) {
				this.RemoveIFElement(isSameIFElement);
			}
		}
	}
}
iFelements = new iFelementsObj();
	// Stoyan work, keep unchanged
jQuery( function( $ ){
	// fix ie6 background flicker problem.
	if ( $.browser.msie == true ) {
		try{
			document.execCommand('BackgroundImageCache', false, true);
		} catch( e ) { }
	}
	$("#page_tabs").tabs();
	$("#module_menu ul").Treeview();
	$("div.module_options li.settings a")
		.unbind("click")
		.bind("click", function() {
			$(this).next("ul").toggle();
		}
	);
	
	// move button
	$('div.module_options li.move a').unbind("mousedown");
	$('div.module_options li.move a').bind("mousedown", function(){
			sortable_enable();
	});
	$('div.module_options li.move a').unbind("mouseup");
	$('div.module_options li.move a').bind("mouseup", function(){
			sortable_disable();
	});
	$("div.module_options li.move a").click( function() {
		if ($(this).is(".func_button")) {
			//var ul_offset_before = $(this).next("ul").offset(); //add IE6 fix form appear on the top
			//var ul_height_before = $(this).next("ul").height(); //add IE6 fix form appear on the top
			$(this).next("ul").toggle();
			//var ul_offset = $(this).next("ul").offset(); //add IE6 fix form appear on the top
			//var ul_height = $(this).next("ul").height(); //add IE6 fix form appear on the top
//window.alert("offset_left="+ul_offset.left+"; offset_top="+ul_offset.top);
//window.alert("ul_height="+ul_height);
			//iFelements.ToggleIFElement(ul_offset, ul_height, ul_offset_before, ul_height_before);
		} else {
/***
var ul_offset = $(this).next("ul").offset();
var ul_height = $(this).next("ul").height();
window.alert("offset_left="+ul_offset.left+"; offset_top="+ul_offset.top);
window.alert("ul_height="+ul_height);
****/
//window.alert("$(this).attr(info)="+$(this).attr("info"));
			module_id = $(this).attr("info");
			current_column = $(this).parents("div.column");
			current_module = $("#module_" + module_id);
			X = parseInt(current_column.children("div.module").index(current_module[0]));
			Y = parseInt(current_column.attr("info"));
			action = $(this).attr("title").toLowerCase();
			switch (action)
			{
				case "up" : 
					if (X != 0) {
						current_column.children().eq(X - 1).before(current_module);
						snapshot();
					};
				break;
				case "down" :
					current_childs = current_column.children();
					if (X != current_childs.size() - 1) {
						current_childs.eq(X + 1).after(current_module); 
						snapshot();
					};
				break;
				
				case "left" :
					if (Y > 0) {
						tab_num = $('#page_tabs').activeTab() - 1;
						left_column = $("#column_" + tab_num + "_" + (parseInt(Y) - 1));
						left_childs = left_column.children();
						left_childs_cnt = left_childs.size();
						if (left_childs_cnt > 0) {
							new_index = X <= (left_childs_cnt - 1) ? X : left_childs_cnt;
							if (new_index > 0) {
								left_childs.eq(new_index - 1).after(current_column.children().eq(X));
							} else {
								left_childs.eq(new_index).before(current_column.children().eq(X));
							}
						}else {
							left_column.append(current_column.children().eq(X));
						}
						snapshot();
					};
				break;
				case "right" :    
					if (Y < 3) {
						tab_num = $('#page_tabs').activeTab() - 1;
						right_column = $("#column_" + tab_num + "_" + (parseInt(Y) + 1));
						right_childs = right_column.children();
						right_childs_cnt = right_childs.size();
						if (right_childs_cnt > 0) {
							new_index = X <= (right_childs_cnt - 1) ? X : right_childs_cnt;
							if (new_index > 0) {
								right_childs.eq(new_index - 1).after(current_column.children().eq(X));
							} else {
								right_childs.eq(new_index).before(current_column.children().eq(X));
							}
						} else {
							right_column.append(current_column.children().eq(X));
						}
						snapshot();
					}
				break;
			}
			$(this).parents("ul:first").toggle();
			return false;    
		}
	});

	// close button
	$("div.module_options li.close a").click( function() {
		var state = confirm("Are you sure you want to close this module?");
		if( state ){
			id = $(this).attr("info");
			coord = getModuleXY( $(this) );
			$("#module_"+id).remove();
			closeCallback(coord[0], coord[1], id);
		}
	});

	// color buttons
	$("#content div.module_options li.color_changer a").click( function() {
		a = $(this);
		$.each(["orange", "yellow", "green", "blue", "red"], function(i, n){
			a.parents("div.module").removeClass(n);
		});
		newcolor = $(this).attr("title").toLowerCase();
		$(this).parents("div.module").addClass(newcolor);
		$(this).parents("li.color_changer:first").parent("ul").hide();
		changeColorCallback($(this).attr("info"), newcolor);
		}
	);
	// minimize button
	$("div.module_options li.minimize a").click( function(){
		coord = getModuleXY($(this));
		minimizeCallback(coord[0], coord[1], $(this).attr("info"));
		$(this).parents("div.module_head:first").siblings("div.module_body").toggle(500);
	});

	// refresh button
	$("div.module_options li.refresh a").click(function(){
		module_id = $(this).attr("info");
		module = $("#module_" + module_id);
		eval( "_show"+module_id+"()" );
	});

	//tabs close buttons
	$("#page_tabs > ul > li:gt(0) > span.close_button").click( function() {
		closeTabCallback($(this).prev().attr("info"));
	});

	// hide/show the left menu
	$("li#module_menu_button a").click( function() {
		$("td#site_frame_left").toggle();
		$("#wrapper").toggleClass("opened");
	});

	// hide/show settings
	$("#site_settings_button a, #site_settings a.close_button").click( function() {
		$("div#site_cloack").toggle();
		$("div#site_settings").toggle();
		$("html").toggleClass('cloacked');
	});
	if ( $("#show_setting_form").length) {
		$("#site_settings_button a").click();
	}

	// hide/show login
	$("#user_login_button a, #user_login a.close_button").click( function() {
		$("div#site_cloack").toggle();
		$("div#user_login").toggle();
		$("html").toggleClass('cloacked');
	});
	if ( $("#show_login_form").length) {
		$("#user_login_button a").click();
	}

	// hide/show register
	$("#user_registration_button a, #site_register a.close_button").click( function() {
		$("div#site_cloack").toggle();
		$("div#site_register").toggle();
		$("html").toggleClass('cloacked');
	});
	if ($("#show_register_form").length){
		$("#user_registration_button a").click();
	}
	$("#feed_submit_button a, #feed_submit a.close_button").click( function() {
		$("div#site_cloack").toggle();
		$("div#feed_submit").toggle();
		$("html").toggleClass('cloacked');
	});
	function init_sortable(){
		//over
		$('div.module_options li.drag_and_drop a').unbind("mousedown");
		$('div.module_options li.drag_and_drop a').bind("mousedown", function(){
			sortable_enable();
		});
		
		//out
		$('div.module_options li.drag_and_drop a').unbind("mouseup");
		$('div.module_options li.drag_and_drop a').bind("mouseup", function(){
			sortable_disable();
		});
	};
	init_sortable();
});
function newWin(path,w,h,r,s) {
	childWindow = window.open(path,"my_win",'height='+h+',width='+w+',left='+((screen.width - w) / 2)+',top='+((screen.height - h) / 2)+',resizable='+r+',location=no,scrollbars='+s+',menubars=no,toolbars=no');
}
function sortable_enable(){
		try{
			for( var i in o = tabs_array ){
				$("#column_" + o[i] + "_0").sortable( sort_conf_new(o[i],1,2) );
				$("#column_" + o[i] + "_1").sortable( sort_conf_new(o[i],0,2) );
				$("#column_" + o[i] + "_2").sortable( sort_conf_new(o[i],0,1) );
			}
		} catch( e ){}
};
function sortable_disable(){
		try{
			for( var i in o = tabs_array ){
				$("#column_" + o[i] + "_0").sortable( "disable" );
				$("#column_" + o[i] + "_1").sortable( "disable" );
				$("#column_" + o[i] + "_2").sortable( "disable" );
			}
		} catch( e ){}
};
function sort_conf_new (tab,a,b){
		var conf = {
			connectWith:["#column_"+tab+"_" + a, "#column_"+tab+"_" + b],
			update:function( ui, event ){
				sortUpdate(0);
			},
			stop: function( ui, event ){
				sortable_disable();
			}
		};
		return conf;
};
_snap_timer_ = 0;
//hotmail
// hotmail:item
hotmail_n = function (){
}
hotmail_n.prototype.init = function( id ){
	hotmail_m.init( id );
}
// hotmail:main
var hotmail_m = {
	id:0,
	hold:"hotmail_unread_mail",
	logout:function(){
		var out = '';
		out += '<strong>Hotmail account - logged</strong>';
		out += '<button type="submit">Logout</button>';
		out += '<span class="clear"></span>';
		out += '</form>';
		return out;
	},
	login:function(){
		var out = '';
		out += '<strong>Hotmail account - not logged</strong>';
		out += '<label><strong>Login name</strong></label>';
		out += '<input type="text" name="username"/>';
		out += '<label><strong>Password</strong></label>';
		out += '<input type="password" name="password"/>';
		out += '<button type="submit">Login</button>';
		out += '<span class="clear"></span>';
		out += '</form>';
		return out;
	},
	show:function( id ){
		$("#"+hotmail_m.hold + id ).html("<p>Loading...</p>");
		var success = function( data ){
			hotmail_m.processJson( id, data );
		}
		$.ajax({
			type: "POST",
			url: conf.base_url,
			data: {m:id, a:'show'},
			success: success,
			async: conf.async,
			global: false,
			dataType:"json"
		});
	},
	processJson:function( id, data ){
		var out, str;
		if(data!= null && data != 'undefined' && data.items != null && data.items != 'undefined'){
			var out = hotmail_m.logout();
			var str = hotmail_m.prepare( id, data );
		} else {
			var out = hotmail_m.login();
			var str = PLEASE_CLICK; 
		}
		$("#login_"+id ).html(out);
		$("#hotmail_unread_mail"+id).html(str); 
	},
	prepare:function(id, data){
		var html = '';
		if( data.error != undefined && data.error == 1 ){
			html += '<p class="description">Incorrect username or password.</p>';
		}else{
			html += '<div class="unread_mail">';
			html += '<p>You have '+ data.fullcount+' unread mails</p>';
			html += '</div>';
			html += '<div class="last_mail">';
			for( var i in o = data.items ) {
				html += '<blockquote class="media_item_3">';
				html += '<h3><a>'+ o[i].title +'</a></h3>';
				html += '<p class="description">From: '+ o[i].author +'</p>';
				html += '</blockquote>';
			}
			html += '</div>';
			if( data.count > 0){
				var pg_div = 'hotmail_pager_'+ id;
				html += '<div id="' + pg_div + '" class="pager">';
				html += __pager(id, data);
				html += '</div>';
			}
		}
		return html;
	},
	init:function( id ){
		// settings
		$("#settings_" + id ).submit( function(){
			var div = "#settings_" + id;  
			var label = $(div+" :input").fieldValue()[0];
			var rows =  $(div+" :input").fieldValue()[1];
			$.post( conf.base_url, { m: id, a:'settings',l: label, r: rows }, function(data){
				core.setTitle( id, label);
				$(div).parents("li.first").parent("ul").hide();
			});
			hotmail_m.show( id );
			return false;  
		});
		// login
		$("#login_" + id).submit(function(){
			var div = "#login_" + id;
			var username = $(div+" :input").fieldValue()[0];
			var password = $(div+" :input").fieldValue()[1];
			if( username == 'undefined' || username == undefined ) username = '';
			if( password == 'undefined' || password == undefined ) password = '';
			$.post( conf.base_url, {m: id, a:'account',u_name: username, u_pass: password }, function(data){
				$(div).parents("li.first").parent("ul").hide();
				hotmail_m.show( id );
			});
			return false;
		});
		hotmail_m.show( id );
	}
}
// hotmail:end

// yahoo:item
function yahoo_show( id ){
	yahoo_m.show( id );
}
yahoo_n = function (){
};
yahoo_n.prototype.init = function( id ){
	yahoo_m.init( id );
}
// yahoo:main
var yahoo_m = {
	hold:"yahoo_unread_mail",
	logout:function(){
		var out = '';
		out += "<strong>Yahoo account - granted</strong>";
		out += "<button type='submit'>Logout</button>";
		out += "<span class='clear'></span>";
		out += "</form>";
		return out;
	},
	login:function( id ){
		var out = '';
		out += '<strong>Yahoo account - access not granted</strong>';
		out += '<p>You can grand access to your yahoo mail inbox:';
		out += '<b style="cursor:pointer" onclick="newWin(\'http://www.page-flakes.com/modules/yahoo/mail/?appdata='+id+'\', 960, 460, \'yes\',\'yes\');"> -> "grand access"</b>';
		out += '</p>';
		//out += '<label><strong>Login name</strong></label>';
		//out += '<input type="text" name="username"/>';
		//out += '<label><strong>Password</strong></label>';
		//out += '<input type="password" name="password"/>';
		//out += '<button type="submit">Login</button>';
		//out += '<span class="clear"></span>';
		//out += '</form>';
		return out;
	},
	show:function( id ){
		$("#" + yahoo_m.hold + id ).html( lang.loading );
		var success = function( data ){
			yahoo_m.processJson( id, data );
		}
		$.ajax({
			type: "POST",
			url: conf.base_url,
			data: {m:id, a:'show'},
			success: success,
			async: conf.async,
			global: false,
			dataType:"json"
		});
	},
	processJson:function( id, data ){
		var out, str;
		if(data!= null && data != 'undefined' && data.items != null && data.items != 'undefined'){
			var out = yahoo_m.logout();
			var str = yahoo_m.prepare(id, data);
		} else {
			var out = yahoo_m.login(id);
			var str = '<strong>Yahoo account - access not granted</strong>';
			str += '<p>You can grand access to your yahoo mail inbox:';
			str += '<b style="cursor:pointer" onclick="newWin(\'http://www.page-flakes.com/modules/yahoo/mail/?appdata='+id+'\', 960, 460, \'yes\',\'yes\');"> -> "grand access"</b>';
			str += '</p>';
		}
		$("#login_"+id ).html(out);
		$( '#yahoo_unread_mail' + id ).html(str); 
	},
	prepare:function(id, data){
		var html = '';
		html += '<div class="unread_mail"><p>You have ' + data.fullcount+' unreaded mails</p></div>';
		html += '<div class="last_mail">';
		if( data.items.length > 0 ) {
			for( var i in o = data.items ) {
				html += '<blockquote class="media_item_3">';
				html += '<h3><a href="'+o[i].url+'" target="_blank">' + o[i].title + '</a></h3>';
				if( o[i] != undefined) {
					if( o[i].summary != 'undefined' && o[i].summary != undefined && o[i].summary != null){
						html += '<p class="description">' + o[i].summary +'</p>';
					}
				}
				html += '</blockquote>';
			}
		}
		html += '</div>';
		if( data.count > 0 ) {
			var pg_div = 'yahoom_pager_'+ id;
			html += '<div id="' + pg_div + '" class="pager">';
			html += __pager(id, data);
			html += '</div>';
		}
		return html;
	},
	init:function( id ){
		// settings
		$("#settings_" + id ).submit( function(){
			var div = "#settings_" + id;  
			var label = $(div+" :input").fieldValue()[0];
			var rows =  $(div+" :input").fieldValue()[1];
			$.post( conf.base_url, { m: id, a:'settings',l: label, r: rows }, function(data){
				$(div).parents("li.first").parent("ul").hide();
				core.setTitle( id, label);
			});
			yahoo_m.show( id );
			return false;  
		});
		// login
		$("#login_" + id).submit(function(){
			var div = "#login_" + id;
			var username = $(div+" :input").fieldValue()[0];
			var password = $(div+" :input").fieldValue()[1];
			if( username == 'undefined' || username == undefined ) username = '';
			if( password == 'undefined' || password == undefined ) password = '';
			$.post( conf.base_url, {m: id, a:'account',u_name: username, u_pass: password }, function(data){
				$(div).parents("li.first").parent("ul").hide();
				//jsondata = $.parseJSON(data);
				yahoo_m.show( id );
			});
			return false;
		});
		// load
		yahoo_m.show( id );
	}
}
// weather:item 
function weather_n(){
	this.locations = [];
};
weather_n.prototype.init = function( id ) {
	weather.init( id );
}
// weather:main 
weather = {
	show:function( id ){
		var target = $("#weather_body_" + id);
		target.html( lang.loading );
		var success = function( reply ){
			target.html( weather.prepare( reply ) );
		}
		$.ajax({
			type: "POST",
			dataType:"json",
			url: conf.base_url,
			data: {m: id, a:'show'},
			success: success,
			async: conf.async,
			global: false
		});
	},
	prepare:function( data ){
			var html = '';
			if( data != null && data.loc != null && data.loc != 'undefined')
			{
				html += '<p>'+ data.loc.place +'</p>';
				html += '<ul class="clearfix">';
				for( var i in o = data.arr ) {
					html += '<li class="sunny"><strong>'+o[i].day+'</strong>';
					html += '<img src="' + conf.base_url + o[i].pic + '" />';
					html += '<small>'+o[i].low+'° / '+o[i].hi+'° ' + o[i].grad + '</small></li>';
				}
				html += '</ul>';
			} else {
				html += '<ul class="clearfix">';
				html += '<li><center>Cannot find location!<br />Please choose manually!</center></li>';
				html += '</ul>';
			}
			html += '<p><small>Powered by: <a href="http://www.weather.com/?prod=xoap&par=1038436701" target="_blank">The Weather Channel ®</a></small></p>';
			return html;
		},
		init:function( id ){
			// settings
			$("#settings_" + id ).submit(function() {
				var div =  "#settings_" + id;
				var label = $(div+" :input").fieldValue()[0];
				var success = function(){
					core.setTitle( id, label);
					$(div).parents("li.first").parent("ul").hide();
				}
				$.post( conf.base_url, {m:id, a:'settings',l: label } , success );
				return false;
			});
			// scale
			$("#scale_" + id ).submit(function() {
				var div = "#scale_" + id;
				var s = $(div+" :input").fieldValue()[0];
				var success = function( reply ){
					$(div).parents("li.first").parent("ul").hide();
					weather.show( id );
				};
				$.post( conf.base_url, {m:id, a:'scale', s: s }, success );
				return false;
			});
			// search
			$("#search_" + id).submit(function() {
				var div = "#search_" + id;
				var s = $(div+" :input").fieldValue()[0];
				var success = function( reply ){
					var o = eval("weather_"+id);
					o.locations = reply;
					var html = '<li class="first" id="f2'+id+'" >';
					if( o.locations.length == 0 ) {
						html += 'No places found for query "' + s + '"!'
					} else {
						html += '<form id="search2_'+id+'">';
						html += '<strong>Find location</strong>';
						html += '<select name="loc" class="select">';
						for( var i in o.locations ){
							html += '<option label="'+o.locations[i].place+'" value="'+o.locations[i].locID+'">'+o.locations[i].place+'</option>';
						}
						html += '</select>';
						html += '<button type="submit">Choose</button>';
						html += '<span class="clear"></span>';
						html += '</form>';
					}
					html += '</li>';
					$("#choise_" + id ).html( html );

					// search 2
					$("#search2_" + id).submit(function(){
						var o = eval("weather_"+id);
						var url = conf.base_url;
						var s = $("#search2_" + id + " :input").fieldValue()[0];
						var locId = s;
						var place = null;
						for( var i in o.locations ) {
							if( o.locations[i].locID == locId) {
								place = o.locations[i].place;
								break;
							}
						}
					var success = function(){
						$("#choise_" + id ).hide();
					};
					$.post( conf.base_url, { m:id, a:'set', locID: locId, place: place}, success );
					$(div).parents("li.first").parent("ul").hide();
					weather.show( id );
					return false;
				});
				$("#choise_" + id ).show();
			}
			$.post(conf.base_url,{m:id,a:'find',s:s},success,"json");
			return false;
		});
		weather.show( id );
	}
}
// google:item
google_n = function (){
	this.show = function( id ){
		$("#" + "gmail_unread_mail" + id ).html( lang.loading );
		var success = function( data ){
			data = $.secureEvalJSON( data );
			google_m.processJson( id, data );
		}
		$.ajax({
			type: "POST",
			url: conf.base_url,
			data: { m: id, a:'show' },
			success: success,
			async: conf.async,
			global: false
		});
	};
}
google_n.prototype.init = function( id ){
	google_m.init( id );
}
// google:main
var google_m = {
	id:0,
	hold:"gmail_unread_mail",
	logout:function(){
		var out = '';
		out += '<strong>Gmail account - logged</strong>';
		out += '<button type="submit">Logout</button>';
		out += '<span class="clear"></span>';
		out += '</form>';
		return out;
	},
	login:function(){
		var out = '';
		out += '<strong>Gmail account - not logged</strong>';
		out += '<strong>Login name</strong>';
		out += '<input type="text" name="username"/>';
		out += '<strong>Password</strong>';
		out += '<input type="password" name="password"/>';
		out += '<button type="submit">Login</button>';
		out += '<span class="clear"></span>';
		out += '</form>';
		return out;
	},
	show:function( id ){
		$("#"+google_m.hold + id ).html("<p>Loading...</p>");
		var success = function( data ){
			data = $.secureEvalJSON( data );
			google_m.processJson( id, data );
		}
		$.ajax({
			type: "POST",
			url: conf.base_url,
			data: {m:id, a:'show'},
			success: success,
			async: conf.async,
			global: false
		});
	},
	processJson:function( id, data ){
		var out, str;
		if(data!= null && data != 'undefined' && data.items != null && data.items != 'undefined'){
			var out = google_m.logout();
			var str = google_m.result_Gmail(id, data);
		} else {
			var out = google_m.login();
			var str = PLEASE_CLICK; 
		}
		$("#login_"+id ).html(out);
		$("#gmail_unread_mail"+id).html(str); 
	},
	result_Gmail:function(id, data){
		var html = '';
		html += '<div class="unread_mail">';
		html += '<p>You have '+ data.fullcount+' unreaded mails</p>';
		html += '</div>';
		html += '<div class="last_mail">';
		for( var i in data.items ) {
			html += '<blockquote class="media_item_3">';
			html += '<h3><a href="'+data.items[i].url+'" target="_blank">'+ data.items[i].title +'</a></h3>';
			html += '<p class="description">'+ data.items[i].summary +'</p>';
			html += '</blockquote>';
		}
		html += '</div>';
		if( data.count > 0){
			var pg_div = 'gmail_pager_'+ id;
			html += '<div id="' + pg_div + '" class="pager">';
			html += __pager(id, data);
			html += '</div>';
		}		
		return html;
	},
	init:function( id ){
		// settings
		$("#settings_" + id ).submit( function(){
			var div = "#settings_" + id;  
			var label = $(div+" :input").fieldValue()[0];
			var rows =  $(div+" :input").fieldValue()[1];
			$.post( conf.base_url, { m: id, a:'settings',l: label, r: rows }, function(data){
				setTitle( id, label);
				$(div).parents("li.first").parent("ul").hide();
			});
			google_m.show( id );
			return false;  
		});
		// login
		$("#login_" + id).submit(function(){
			var div = "#login_" + id;
			var username = $(div+" :input").fieldValue()[0];
			var password = $(div+" :input").fieldValue()[1];
			if( username == 'undefined' || username == undefined ) username = '';
			if( password == 'undefined' || password == undefined ) password = '';
			$.post( conf.base_url, {m: id, a:'account',u_name: username, u_pass: password }, function(data){
				$(div).parents("li.first").parent("ul").hide();
				jsondata = $.parseJSON(data);
				google_m.show( id );
			});
			return false;
		});
		// load
		google_m.show( id );
	}
}
//calendar
// calendar:item
function calendar_n(){
	this.data = {};
	this.natDays = false;
}
calendar_n.prototype.init = function( id ){
	calendar_m.init( id );
}
// calendar:main
calendar_m = {
	show:function( id ){
		var target = $("#calendar_body_" + id);
		//target.html( lang.loading );
		var success = function( reply ){
			var o = eval("calendar_" + id );
			o.data = reply.events;
			target.html( calendar_m.prepare( id, reply ) );
		}
		$.post(
			conf.base_url,
			{m:id, a:'show',date:calendar_m.getMysqlDate( id )},
			success,
			"json"
		);
	},
	fix:function( str ){
		str = str.replace(/'/g,'&apos;');
		str = str.replace(/"/g,'&quot;');
		return str;
	},
	event_row:function( id, obj ){
		var d = new Date();
		var style = '';
		var date = obj.date.split('-');
		var html2 = '';
		html2 += '<td><input class="nostyle" type="checkbox" onclick="calendar_m.done('+ id+','+obj.id+');"';
		if( obj.done == 1 ) {
			html2 += ' checked="checked"';
		}
		if( d.getDate() == Number(date[2]) && ( (d.getMonth() + 1) == Number(date[1]) ) && d.getFullYear() == Number( date[0] ) ){
			style = 'today';
		}
		if( ( d.getDate() + 1) == Number(date[2]) && ( (d.getMonth() + 1) == Number(date[1]) ) && d.getFullYear() == Number( date[0] ) ){
			style = 'tomorrow';
		}
		html2 += '> <span class="calendar_dates '+style+'" style="font-size:9px">'+date[2]+'/'+date[1]+'/'+date[0]+'</span>&nbsp;';
		val = calendar_m.fix( obj.text );
		if( obj.done == 1 ) {
			html2 += '<strike>'+val+'</strike>';
		} else {
			html2 += val;
		}
		html2 += '</td>';
		html2 += '<td width="16" align="right"><a class="my_calendar_edit" href="javascript:calendar_m.edit('+id+','+ obj.id+');"></a></td>';
		html2 += '<td width="16" align="right"><a class="my_calendar_remove" href="javascript:calendar_m.remove('+id+','+obj.id+');"></a></td>';
		return html2;
	},
	prepare:function( id, reply ){
		var html = '';
		html += '<table cellpadding="4" cellspacing="0" width="100%">';
		html += '<tr id="c_'+id+'"><td style="padding:6px"><table cellpadding="0" cellspacing="0" width="100%">';
		var results = reply.events;
		if( results != undefined ) {
			var len = results.length;
			if( len == 0 ){
				html += '<tr><td><p>No events on this day.</p></td></tr>';
			} else {
				for( var i in results ) {
					html += '<tr id="t_' + results[i].id+'">';
					html += calendar_m.event_row( id, results[i] );
					html += '</tr>';
				}
			}
		}
		html += '</table>';
		html += '</td></tr>';
		html += '</table>';
		html += '<div id="addb_'+id+'"><span><a class="my_calendar_add" href="javascript:calendar_m.add('+id+');">add new event</a></span></div>';
		if( reply.pager != undefined)
		{
			html += '<div id="tasks_pager' + id + '" class="pager">';
			html += __pager( id, reply );
			html += '</div>';
		}
		return html;
	},
	edit:function( task_id, id ){
		var holder = eval("calendar_"+task_id);
		event = calendar_m.findEventById( task_id, id);
		var eventDate = event.date.split('-');
		holder.date = {
			year:eventDate[0],
			month:eventDate[1],
			day:eventDate[2]
		}
		content = calendar_m.edit_event_row( task_id, event );
		$('.ui-datepicker-'+task_id).datepicker("setDate", new Date(Number(eventDate[0]),Number(eventDate[1])-1,Number(eventDate[2])));
		$( '#t_' + event.id ).html( content );
		$( '#n_event' + event.id ).focus();
	},
	init:function( id ){
		var hold = eval("calendar_" + id );
		if( ! hold.natDays )
		{
			calendar_m.loadDays( id );
			return;
		}
		var natDays = hold.natDays;
		function myDays(date){
			for (i = 0; i < natDays.length; i++){
				if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {  
					return [true, natDays[i][2] + '_day'];
				}
			}
			return [true, ''];
		} 
		//datepicker
		var calendar_conf = function( id ){
			return {
				customRange: null,
				numberOfMonths: 1,
				beforeShowDay: myDays,
				changeFirstDay: true,
				onChangeMonthYear: function(date, next) {
				},
				onSelect:function( date, next ){
					var date = date.split('/');
					var hold = eval("calendar_" + id );
					hold.date = {
						year:date[2],
						month:date[0],
						day:date[1]
					};
					calendar_m.show( id );
				}
			};
		}
		$(".ui-datepicker-" + id ).datepicker("destroy");
		$(".ui-datepicker-" + id ).datepicker( calendar_conf( id ) );
		//get the current date and set to holder
		var hold = eval("calendar_"+id);
		myDate = $(".ui-datepicker-" + id ).datepicker("getDate");
		hold.date = {
			year:myDate.getFullYear(),
			month:myDate.getMonth() + 1,
			day:myDate.getDate()
		};
		//
		$("#settings_" + id ).submit(function(){
			var div =  "#settings_" + id; 
			var label = $(div+" :input").fieldValue()[0];
			var rows = $(div+" :input").fieldValue()[1];
			$.post( conf.base_url, { m:id, a:'settings', l: label, r:rows }, function() {
				$(div).parents("li.first").parent("ul").hide();
				core.setTitle( id, label );
				calendar_m.show( id );
			});
			return false;
		});
		calendar_m.show( id );
	},
	findEventById:function( calendar_id, id ){
		var o = eval("calendar_" + calendar_id );
		for( var i in o.data ){
			if( o.data[i].id == id )
				return o.data[i];
		}
		return null;
	},
	ge:function( id ){
		return document.getElementById ? ( document.getElementById(id) ? document.getElementById(id) : null ) : document.all[id];
	},
	edit_event_row:function( id, obj ){
		var html 	= '';  
		var obj2 	= calendar_m.ge( "c_" + id );
		var oWidth	= obj2.offsetWidth - 30;
		var style	= ' class="calendar_edit_entry" style="width:'+oWidth+'px"'; 
		html += '<td>&nbsp';
		val = calendar_m.fix( obj.text );
		html += '<input name="n_event'+obj.id+'" id="n_event'+obj.id+'" type="text" maxlength="50" size="20" value="'+val+'" '+ style +' nblur="calendar_m.save('+id+','+ obj.id+');" />';   
		html += '<td width="16" align="right"><a class="my_calendar_edit" href="javascript:calendar_m.save('+id+', '+ obj.id+');"></a></td>';
		html += '<td width="16" align="right">';
		html += '<a class="my_calendar_remove" href="javascript:calendar_m.remove('+id+','+obj.id+');"></a></td>';
		return html;
	},
	add:function( id ){
		var o = eval("calendar_"+id);
		var date = calendar_m.getMysqlDate( id );
		$.post(
			conf.base_url,
			{m:id,a:'add',date:date},
			function(){
				o.natDays.push([date.split('-')[1],date.split('-')[2],"events"]);
				calendar_m.updateOptions( id );
				calendar_m.show( id );
			}
		);
	},
	getMysqlDate:function( id ){
		var hold	=	eval("calendar_"+id);
		var month	=	hold.date.month < 10 ? '0'+hold.date.month : hold.date.month;
		var day		=	hold.date.day < 10 ? '0'+hold.date.day : hold.date.day;
		var date	=	hold.date.year+'-'+month+'-'+day;
		return date;
	},
	remove:function( task_id, id ){
		$.post(conf.base_url, {m:task_id,a:'remove',t:id},function(){
			$('tr#t_'+id).remove();
			//calendar_m.loadDays( task_id );
		});
	},
	save:function( task_id, id ){
		var text = $('#n_event'+ id).val();
		//$('.ui-datepicker-' + task_id ).datepicker("setDate", new Date() );
		$.post(
			conf.base_url,
			{m:task_id,a:'save',t:id,text:text,date:calendar_m.getMysqlDate( task_id ) },
			function(){
				calendar_m.show( task_id );
			}
		);
	},
	done:function( task_id, id ){
		var o = calendar_m.findEventById( task_id, id);
		o.done = Number( o.done );
		o.done = o.done ? 0 : 1;
		$.post(conf.base_url, { m:task_id, t:id, done:o.done, a:'done'}, function(){
			calendar_m.show( task_id );
		});
	},
	pager:function( id, page ){
		var success = function( data ){
			var o = eval("calendar_"+id);
			o.data = data.events;
			$("#calendar_body_" + id ).html( calendar_m.prepare( id, data) ); 
		};
		$.ajax({
			type: "POST",
			dataType:"json",
			url: conf.base_url,
			data: {m:id,a:'pager',p:page,date:calendar_m.getMysqlDate( id )},
			success: success,
			async: conf.async,
			global: false
		});
	},
	loadDays:function( id ){
		var o = eval("calendar_" + id );
		var success = function( data ){
			var rawEvents = data.events;
			o.natDays = [];
			for( var i in rawEvents ){
				o.natDays.push([rawEvents[i].date.split('-')[1],rawEvents[i].date.split('-')[2],'events',rawEvents.id]);
			}
			calendar_m.init( id );
		}
		//, date:calendar_m.getMysqlDate( id )
		$.ajax({
			type: "POST",
			dataType:"json",
			url: conf.base_url,
			data: {m:id, a:"natDays",date:''},
			success: success,
			async: conf.async,
			global: false
		});
		//o.natDays = [[12, 15, 'events'],[12, 25, 'events']];
	},
	loadDaysSingle:function( id ){
		var o = eval("calendar_" + id );
		var success = function( data ){
			var rawEvents = data.events;
			o.natDays = [];
			for( var i in rawEvents ){
				o.natDays.push([rawEvents[i].date.split('-')[1],rawEvents[i].date.split('-')[2],'events',rawEvents.id]);
			}
			calendar_m.updateOptions( id );
		}
		$.ajax({
			type: "POST",
			dataType:"json",
			url: conf.base_url,
			data: {m:id, a:"natDays",date:''},
			success: success,
			async: conf.async,
			global: false
		});
	},
	updateOptions:function( id ){
		$(".ui-datepicker-" + id ).datepicker( calendar_m.calendar_conf( id ) );
	},
	calendar_conf:function( id ){
		var o = eval("calendar_"+id);
		var natDays = o.natDays;
		function myDays(date){
			for (i = 0; i < natDays.length; i++){
				if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {  
					return [true, natDays[i][2] + '_day'];
				}
			}
			return [true, ''];
		}
		return {
			customRange: null,
			numberOfMonths: 1,
			beforeShowDay: myDays,
			changeFirstDay: true,
			onChangeMonthYear: function(date, next) {
				
			},
			onSelect:function( date, next ){
				var date = date.split('/');
				var hold = eval("calendar_" + id );
				hold.date = {
					year:date[2],
					month:date[0],
					day:date[1]
				};
				calendar_m.show( id );
			}
		};
	}
};

/* task:item */
function task_n(){
	this.data = {};
}
task_n.prototype.init = function(id){
	task.init(id);
}
/* task:main */
task = {
	page:1,
	show:function( id ){
		var target = $("#tasks_body_" + id);
		//target.html( lang.loading );
		var success = function( reply ){
			var o = eval("task_" + id );
			o.data = reply.tasks;
			target.html( task.prepare( id, reply) );
		}
		$.post(
			conf.base_url,
			{ m:id, a:'show' },
			success,
			"json"
		);
	},
	prepare:function( id, reply ){
		var html = '';
		html += '<table cellpadding="4" cellspacing="0" width="100%">';
		html += '<tr id="c_'+id+'"><td style="padding:6px"><table cellpadding="0" cellspacing="0" width="100%">';
		var results = reply.tasks;
		if( results != undefined || results != 'undefined' )
		{
			var len = results.length;
			if( len == 0 )
			{
				html += '<tr>'
				html += "\t<td><p>You have no tasks!</p></td>";
				html += '</tr>'
			} else {
				for( var i in results ) {
					html += '<tr id="t_' + results[i].id+'">'
					html += task.task_row( id, results[i] )
					html += '</tr>'
				}
			}
		}
		html += '</table>';
		html += '</td></tr>';
		html += '</table>';
		html += '<div id="addb_'+id+'"><span><a href="javascript:add_'+id+'();"><img src="/modules/tasks/img/add.gif" border=0 align="absmiddle" /></a>add new task</span></div>';
		if( reply.pager != undefined)
		{
			html += '<div id="tasks_pager' + id + '" class="pager">';
			html += __pager( id, reply );
			html += '</div>';
		}
		return html;
	},
	task_row:function( id, obj ){
		var html2 = '';
		html2 += '<td><input class="nostyle" type="checkbox" onclick="task.done('+ id+','+obj.id+');"';
		if( obj.done == 1 ) {
			html2 += ' checked="checked"';
		}
		html2 += '>&nbsp;&nbsp;';
		val = task.fix( obj.text );
		if(obj.done==1) {
			html2 += '<strike>'+val+'</strike>';
		} else {
			html2 += val;
		}
		html2 += '</td>';
		html2 += '<td width="16" align="right"><a href="javascript:edit_'+id+'('+ obj.id+');"><img src="/modules/tasks/img/edit.gif" align="absmiddle" /></a></td>';
		html2 += '<td width="16" align="right"><a href="javascript:delete_'+id+'('+ obj.id+');"><img src="/modules/tasks/img/deleteLink.gif" align="absmiddle" /></a></td>';
		return html2;
	},
	edit:function( task_id, id ){
		var o = eval("task_" + task_id );
		var data = { tasks: o.data };
		str = task.prepare( task_id, data);
		$("#tasks_body_" + task_id ).html( str );
		t = task.findTaskById( task_id, id);
		v = task.edit_task_row( task_id, t);
		$( '#t_' + t.id ).html( v );
		$( '#n_task' + t.id ).focus();
	},
	fix:function( str ){
		str = str.replace(/'/g,'&apos;');
		str = str.replace(/"/g,'&quot;');
		return str;
	},
	init:function( id ){
		$("#settings_" + id ).submit(function(){
			var div =  "#settings_" + id; 
			var label = $(div+" :input").fieldValue()[0];
			var rows = $(div+" :input").fieldValue()[1];
			$.post( conf.base_url, { m:id, a:'settings', l: label, r:rows }, function(data) {
				$(div).parents("li.first").parent("ul").hide();
				core.setTitle( id, label); 
				task.show( id );
			});
			return false;
		});
		task.show( id );
	},
	findTaskById:function(task_id, id){
		var o = eval("task_"+task_id);
		for( var i in o.data ){
			if( o.data[i].id == id )
				return o.data[i];
		}
		return null;
	},
	edit_task_row:function( id, obj ){
		var html2 	= '';  
		var obj2 	= _gel( "c_" + id );
		var oWidth	=obj2.offsetWidth - 30;
		var style	='style="width:'+oWidth+'px;height:12px; border:1px dashed #101010;font-size:10px;font-family:Verdana,Arial;"'; 
		html2 += '<td>&nbsp';
		val = task.fix( obj.text )
		html2 += '<input name="n_task'+obj.id+'" id="n_task'+obj.id+'" type="text" maxlength="50" size="20" value="'+val+'" '+ style +' onblur="task.save('+id+','+ obj.id+');"/>';   
		html2 += '<td width="16" align="right"><a href="javascript:save_'+id+'('+ obj.id+');"><img src="/modules/tasks/img/edit.gif" align="absmiddle" /></a></td>';
		html2 += '<td width="16" align="right"><a href="javascript:delete_'+id+'('+ obj.id+');"><img src="/modules/tasks/img/deleteLink.gif" align="absmiddle" /></a></td>';
		return html2;
	},
	save:function( task_id, id ){
		var text = $('#n_task'+ id).val();
		$.post(conf.base_url,{m:task_id,a:'save',t:id,text:text},function(){
			task.show(task_id);
		});
	},
	add:function( id ){
		$.post(
			conf.base_url,
			{ m:id, a:'add' },
			function(){
				task.pager( id, task.page );
				//task.show( id );
			}
		);
	},
	remove:function( task_id, id ){
		$.post(conf.base_url, {m:task_id,a:'remove',t:id},function(){
			$('tr#t_'+id).remove();
			//task.show(task_id);
		});
	},
	done:function( task_id, id ){
		var t = task.findTaskById( task_id, id);
		if(t.done==0){
			t.done=1;
		}else{
			t.done=0;
		}
		$.post(conf.base_url,{m:task_id,t:id,done:t.done,a:'done'},function(){
			task.show( task_id );
		});
	},
	pager:function( id, page ){
		this.page = page;
		$.post(
			conf.base_url,
			{m:id,a:'pager',p:page},
			function(data){
				var o = eval("task_"+id);
				o.data = data.tasks;
				$("#tasks_body_" + id ).html( task.prepare( id, data) ); 
			},
			"json"
		);
	}
};
// adv:item 
function adv_n(){};
adv_n.prototype.init = function( id ){
	adv.init( id );
}
// adv:main 
adv = {
	show:function( id ){
		$("#module_" + id + " > div.module_options li.close > a").unbind();
	},
	init:function( id ){
		$("#settings_" + id ).submit( function(){
			var label = $("#settings_"+id+" :input").fieldValue()[0];
			var success = function(){
				core.setTitle( id, label);
				$("#settings_"+id).parents("li.first").parent("ul").hide();
			}
			$.ajax({
				type: "POST",
				url: conf.base_url,
				data: {m:id, a:'settings',l: label },
				success: success,
				async: conf.async,
				global: false
			});
			return false;
		});
		adv.show(id);
	}
};