// JavaScript Document
//harry
//Inititialize function will initialize desktop
$.extend($.expr[':'], {
	'containsi': function (elem, i, match, array) {
		return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
	}
});
$.fn.sort = function(c) {
	return this.pushStack([].sort.apply(this, arguments), []);
 };
var sortAscending = function(a, b) {
	 return $(a).find("h1").text() > $(b).find("h1").text() ? 1 : -1;
};
var sortDescending = function(a, b) {
	 return $(a).find("h1").text() < $(b).find("h1").text() ? 1 : -1;
};
var orbitDesktop = function(dom){
	orbitDesktopAPI.apply(this);
	o = this;
	this.contentHolder = dom;
	this.themesettings = "";
	this.theme = "4f8d3f493b67fcd05f086359";
	this.transitionTime = 500;
	this.currenthtml = "desktop.html";
	this.currentface = "home";
	this.desktopData = {"home":"","settings":"","work":"","favorite":"","apps_manager":"","sections":"","journal_p":"","appstore":"","orbit":"","books":"","seminar_p":"","research_d":"","research_p":""};
	this.tp = "";
	this.sectionList;
	this.initialize = function(){
			var theme = o.theme;
			var custom = false;
		$.getJSON("/desktop/get_desktop_settings",{"get":"desktop","desktopid":o.desktopId},function(desktopSettings){
			if(desktopSettings){
				if(desktopSettings.theme!="custom"){
					theme = desktopSettings.theme;
				}else{
					theme = "4f8d3f493b67fcd05f086359";
					custom = true;
				}
				o.theme = theme;
				loadTheme(desktopSettings.customtheme,desktopSettings.wallpaper);
			}else{loadTheme();}
		})
		var loadTheme = function(customtheme,customwallpaper){   //This function will load the theme from database
			$.getJSON("/"+o.themefolder+"/"+theme+"/settings/"+theme+".json",function(ts){
				o.themesettings = eval(ts);
				$('head').append( $('
');
						 $(this).append($newcol);
						 $newcol.sortable({connectWith: '.g_col'});
						 grps.push($newcol);
						 $("#group_wrapper").width($("#group_wrapper").width()+225);
					});
					$("div#desktop .g_col").sortable('refresh');
				},
				update:function(){
					if(first){
						first = false;
						var newpostitions = new Array;
						var groupids = new Array;
						$.each($("div#desktop .group"),function(i,grp){
							var groupone = new Array;
							groupids.push($(grp).attr("id"));
							$ul = $(grp).find(".g_col .element");
							$.each($ul,function(){
								groupone.push($(this).attr("id"));
							})
							newpostitions.push(groupone);
						});
						$.post("/desktop/newpositions",{"sectionid":o.sectionId,"newpos":newpostitions,"groupids":groupids});
					}
					var s = $(this).find('.element').length;
						if(s!=0){
							last = $(this).find('.element').eq(s-1).position(),
							lasth = $(this).find('.element').eq(s-1).outerHeight(true);
							if ((last.top+lasth)>528){
								$(this).sortable('cancel');
							}
						}
						$("#group_wrapper ul").each(function(){
							if($(this).find('.element').length == 0)
								$(this).animate({"width":"0px"},500,function(){$(this).remove();});
						})
				},
				receive: function(event, ui){
					var s = $(this).find('.element').length,
						last = $(this).find('.element').eq(s-1).position(),
						lasth = $(this).find('.element').eq(s-1).outerHeight(true);
					if ((last.top+lasth)>528){
						$(ui.sender).sortable('cancel');
					}
				}
			});
			o.tinyscrollbar_ext({
				main: '.tinycanvas'
			})
			o.simple_drop_down();
			$("div#group_wrapper ul li[data-category=app]").click(function(){
				o.appWindow({
					title : $(this).find("a").attr("href"),
					appid : $(this).find("a").attr("href")
				});
			});
		}	
		var loadTiles = function(id){  //This will load tiles for a specific desktop .. id of section has to be passed here to load tiles
			$("div#desktop div#group_wrapper").empty();
			$.getJSON("/desktop/getgroups",{sectionid:id},function(groups){
				var tilecolors = o.themesettings.tilecolor;
				var opacity = ["op05","op06","op07","op08","op09"];
				$.each(groups,function(i,group){
					group.sort(o.sortJSON("position",true,parseInt));
					// var $group = $(''),
					var colindex = 0,
						$group = $('
'),
						$col = $(''),
						$li,
						bdsum = 0,
						bwsum = 0,
						bhsum = 0,
						small = 0,
						single = false;
					$group.append($col);
					for(j=0;j 8 || bhsum > 6){
							bdsum = 0, bhsum = 0, colindex++,j--;
							$group.append('');
						}else{			
							var tilecolor = tilecolors[Math.floor(Math.random()*tilecolors.length)];
							var op = opacity[Math.floor(Math.random()*opacity.length)];
							if(j==0)$group.attr("id",tile.group_id);
							
							if(tile.data_category == "app")
								$li = $(''+tile.title+' '+tile.title+' Loading...
'+section.name+' '+section.name+' '+$(this).html()+'
');
							$("div#app_manager .search_result").prepend($newelement);
						})
					}
				}else{$("div#app_manager #seperator").hide();$("div#app_manager .search_result").empty();}
			}).blur(function(){$(this).val("Search");});
			
			//for Alphabet sorting
			$("div#app_manager a#alphabet_sort_btn").click(function(){
				switch ($(this).attr("href")){
					case "ascending":
						$(this).attr("href","descending").find(".thmtxt").text("Alphabet [Z-A]");
						allApps = $("div#app_manager .group_search .element").sort(sortAscending);
						break;
					case "descending":
						$(this).attr("href","ascending").find(".thmtxt").text("Alphabet [A-Z]");
						allApps = $("div#app_manager .group_search .element").sort(sortDescending);
						break;
				}
				$("div#app_manager #app_list").empty();
				var count = 0, colindex = 0;
				$('#app_list').append('
');
				$.each(allApps,function(i,app){
					count++;
					if( count > 4 ){
						count = 1, colindex+=1;
						$('#app_list').append('
');
						$('.g_col.col'+ colindex).append(app);
					} else {
						$('.g_col.col'+ colindex).append(app);
					}
				})
				return false;
			})
			o.tinyscrollbar_ext({
				main: '.tinycanvas'
			})
		}
		var loadApps = function(){ //this load apps for sorting and searching 
			$.getJSON("/desktop/getapplist",{desktopid:o.desktopId},function(appss){
				var count = 0, colindex = 0;
				$('#app_list').append('
');
				$.each(appss,function(i,apps){
					$.each(apps,function(i,app){
						var $app;
						count++;
						$app = $(''+app.title+' 
');
							$('.g_col.col'+ colindex).append($app);
						} else {
							$('.g_col.col'+ colindex).append($app);
						}
					})
				})
			
				bindHandlers();
			})
		}
		if(!o.desktopData[o.currentface]){
			$(o.contentHolder).empty().load("/desktop/"+target,function(){
				loadApps();
			});
		}else{
			$(o.contentHolder).html(o.desktopData[o.currentface]);
				bindHandlers();
		}
	};
	this.initializeSectionsManager = function(target){ // this is init function for section manager
		o.currenthtml = target;
		o.currentface = "sections";
		var elementParent,element,slabel;
		var bindHandlers = function(){  // this is bind handler for section manager page
			var groupWrapperWidth = 0;
			$("div#sections .group").width(400);
				$("div#sections .group").each(function(){groupWrapperWidth+=$(this).width();})
				groupWrapperWidth+=200;
				groupWrapperHeight = $(".group").height() + 20;
				$("#group_wrapper").width(groupWrapperWidth);
			$("div#sections #group_wrapper .grp").sortable({
				start:function(){
					slabel = $(this).siblings('.section_label');
					slabel.find('li:hidden').stop(1,1).fadeIn(500);
				},
				stop:function(){
					slabel.find('li:not(:nth-child(1))').stop(1,1).fadeOut(500);
				}
			});
			$("div#sections .section_label li:not(:nth-child(1))").droppable({
				drop:function(event, ui){
					elementParent = ui.draggable.parents('.group');
					var $item = $( this ),
						$list = $( '#'+$item.data("category") );
					if($list.children('.element').length>=24){
						o.notify("Section is full.","alert");
					}
					else{
						ui.draggable.hide('fast',function(){
							$(this).appendTo($list).fadeIn();
						});
						$.post("/desktop/save_desktop_settings",{"save":"appnewsection","appid":ui.draggable.attr("id"),"newsectionid":$(this).data("content"),"desktopid":o.desktopId});
						if(o.sectionId == $(this).data("content") || o.sectionId == elementParent.attr("id")){
							o.desktopData["home"]="";
						}
					}
					$(this).find('span.tile').addClass('op06',400);
				},
				over:function(){
				    $(this).find('span.tile').removeClass('op06');
				},
				out:function(){
					$(this).find('span.tile').addClass('op06');
				},
				accept: '.to_drop'
	 		});
			o.tinyscrollbar_ext({
				main: '.tinycanvas'
			})
		};
		var loadApps = function(){ // this loads apps from db to in each sections
			$.getJSON("/desktop/getapplist",{desktopid:o.desktopId},function(appss){
				var $group,$lii,$li;
				var z=0;
				for(section in o.sectionList){
					$group = $('');
					for(x=0;x<4;x++){
						if(x==0){						
							$li = $(''+o.sectionList[z].name+' '+o.sectionList[x].name+' '+app.title+' "+usernm+"
")
									$ul.find("input[type=password]").replaceWith("••••••
");
									$(this).text("Edit").attr("for","edit");
									$(this).parent().find("a[for=delete]").show();
									$ul.find("span.c_status").text("Connected").addClass("c_status_on");
									if(what=="save")
										what="edit";
									saveaccount(usernm,pwd,type,what);
								}
								break;
							case "edit":
								var un = $ul.find("div.usrnm").text();
								$ul.find("div.usrnm").replaceWith('"+account.email+"
")
						$ul.find("input[type=password]").replaceWith("••••••
");
						$ul.find("a[for=new]").text("Edit").attr("for","edit");
						$ul.find("a[for=delete]").show();
						$ul.find("span.c_status").text("Connected").addClass("c_status_on");
					})
					bindHandlers();
				})
				
			})
			
		}
		$(o.contentHolder).empty().load("/desktop/"+target,function(){
			bindHandlers();
			themes();
		});
	};
	this.initializeOrbitTimeline = function(target){
		o.currenthtml = target;
		o.currentface = "orbit";
		var bindHandlers = function(){
			var timeline = new orbitTimeline("#timeline");
			timeline.initialize();
		}
		if(!o.desktopData[o.currentface]){
			$(o.contentHolder).empty().load("/desktop_orbit/"+target,function(){
				bindHandlers();
			});
		}else{
			$(o.contentHolder).html(o.desktopData[o.currentface]);
			bindHandlers();
		}
	};
	this.initializeJournalPapers = function(target){ // this init journal papers
		o.currenthtml = target;
		o.currentface = "journal_p";
		var bindHandlers = function(){ // bind handler for journal paper
			$('.s_menu a').on({
				click: function(){
					if(!$(this).hasClass('active')){
						var tfunc = $(this).attr('href');
						switch(tfunc){
							case 'list':
								list();
							break;
							case 'addpaper':
								addpaper();
							break;
						}
						$('.s_menu a').removeClass('thmc1 thmtxt active');
						$(this).addClass('thmc1 thmtxt active');
					}
				},
				mouseenter: function(){
					if(!$(this).hasClass('active')){
						$(this).switchClass('admtxt','thmc1 thmtxt',0);
					}
				},
				mouseleave: function(){
					var t = $(this).hasClass('active') ? '' : 'thmc1 thmtxt';
					$(this).switchClass(t,'admtxt',0);
				}
			});
		}
		
		var list = function(){ // to open list part in journal papers page
			var journalData;
			var bindHandlers = function(){ // to bind handlers for list page
				o.simple_drop_down();
				o.tinyscrollbar_ext({
					main: '.tinycanvas',
					fill: '.list_t'
				})
				
				$("#journal_selection_options a").click(function(){
					switch($(this).attr("href")){
						case "all":
							$(".list_item_action > .icon-check-empty").switchClass("icon-check-empty","icon-check",0);
							break;
						case "none":
							$(".list_item_action > .icon-check").switchClass("icon-check","icon-check-empty",0);
							break;
					}
					return false;
				})
				$("#journal_view_selection a").click(function(){
					switch($(this).attr("href")){
						case "journal":
						journalview();
						break;
						case "keywords":
						keywordsview();
						break;
						case "title":
						titleview();
						break;
						case "abstract":
						abstractview();
						break;
					}
					return false;
				})
			}
			var bindSecondaryHandlers = function(){
				$("#journal_p div#paper_list a").click(function(){
					if($(this).hasClass("icon-check-empty")){
						$(this).switchClass("icon-check-empty","icon-check",0);
					} else if($(this).hasClass("icon-check")) {
						$(this).switchClass("icon-check","icon-check-empty",0);
					} else if($(this).hasClass("icon-star")){
						$(this).removeClass("icon-star").addClass("icon-star-empty");
					} else if($(this).hasClass("icon-star-empty")){
						$(this).removeClass("icon-star-empty").addClass("icon-star");
					}
					return false;
				})
			}
			var journalview = function(){
				$("#journal_p div#paper_list div.overview").empty();
				var column = $(''),
						counter = 1,
						li;
					$.each(journalData,function(i,journal){
						$.each(journal.papers,function(j,paper){
							li = $(''+journal.title+'
'+paper.title+'
'+paper.title+'
'+paper.keywords+'
'+paper.title+'
'+paper.title+'
'+paper.abstract+paper.abstract+'
'+widge.name+'
Author : '+widge.author+'
Shape : '+shp+'
Status : '+widge.status+'
"+s.name +"  ";
										}
									})
								})
								var section_names = o.getArrayfromJson(o.sectionList,"name");
								var section_links = o.getArrayfromJson(o.sectionList,"_id");
								var s_name_list_not = "";
								$.each(section_names,function(j,sec_name){
									if($.inArray(sec_name,cur_section_names)==-1){
										var sec_link = section_links[j];
										s_name_list_not+= ""+sec_name+"  ";
									}
								})
								li.find("div.status").html("Status : Installed on "+s_name_list);
								if(s_name_list_not)
									li.find("div.not_status").html("Install on "+s_name_list_not);
							}else{
								li.find("div.not_status").html("Install on "+o.sectionList[0].name+"  "+o.sectionList[1].name+"  "+o.sectionList[2].name+"  "+o.sectionList[3].name)+" ";
							}
							//console.log(section_names);			
							column.find("ul").append(li);
							if(counter%4==0){
								$("#apps_store div#widget_list").append(column);
								column = $('');
							}
							counter++;
					})
				$("#apps_store div#widget_list").append(column);
				bindHandlers();
				})
			})
		}
		var onlinestore = function(){
			var bindHandlers = function(){
			}
			$("div#apps_store div#panel_r").load("/desktop_appstore/onlinestore",function(){
				bindHandlers();
			})
		}
		if(!o.desktopData[o.currentface]){
			$(o.contentHolder).empty().load("/desktop_appstore/"+target,function(){
				onlinestore();
				bindHandlers();
			});
		}else{
			$(o.contentHolder).html(o.desktopData[o.currentface]);
			onlinestore();
			bindHandlers();
		}
	}
	this.initializeBooks = function(target){
		o.currenthtml = target;
		o.currentface = "books";
		var bindHandlers = function(){
			$('.s_menu a').on({
				click: function(){
					if(!$(this).hasClass('active')){
						var tfunc = $(this).attr('href');
						switch(tfunc){
							case 'list':
								list();
							break;
							case 'addbook':
								addbook();
							break;
						}
						$('.s_menu a').removeClass('thmc1 thmtxt active');
						$(this).addClass('thmc1 thmtxt active');
					}
				},
				mouseenter: function(){
					if(!$(this).hasClass('active')){
						$(this).switchClass('admtxt','thmc1 thmtxt',0);
					}
				},
				mouseleave: function(){
					var t = $(this).hasClass('active') ? '' : 'thmc1 thmtxt';
					$(this).switchClass(t,'admtxt',0);
				}
			});
		}
		var list = function(){
			var bindHandlers = function(){
				o.simple_drop_down();
				o.tinyscrollbar_ext({
					main: '.tinycanvas',
					fill: '.list_t'
				})
			}
			$("div#books div#panel_r").load("/desktop/books_list",function(){
				bindHandlers();
			})
		}
		var addbook = function(){
			var bindHandlers = function(){
				o.simple_drop_down();
				o.tinyscrollbar_ext({
					main: '.tinycanvas',
					fill: '.s_grid_con'
				})
			}
			$("div#books div#panel_r").load("/desktop/books_add",function(){
				bindHandlers();
			})
		}
		if(!o.desktopData[o.currentface]){
			$(o.contentHolder).empty().load("/desktop/"+target,function(){
				list();
				bindHandlers();
			});
		}else{
			$(o.contentHolder).html(o.desktopData[o.currentface]);
			list();
			bindHandlers();
		}
	}
	this.initializeSeminar = function(target){
		o.currenthtml = target;
		o.currentface = "seminar_p";
		var bindHandlers = function(){
			$('.s_menu a').on({
				click: function(){
					if(!$(this).hasClass('active')){
						var tfunc = $(this).attr('href');
						switch(tfunc){
							case 'list':
								list();
							break;
							case 'addseminar':
								addseminar();
							break;
						}
						$('.s_menu a').removeClass('thmc1 thmtxt active');
						$(this).addClass('thmc1 thmtxt active');
					}
				},
				mouseenter: function(){
					if(!$(this).hasClass('active')){
						$(this).switchClass('admtxt','thmc1 thmtxt',0);
					}
				},
				mouseleave: function(){
					var t = $(this).hasClass('active') ? '' : 'thmc1 thmtxt';
					$(this).switchClass(t,'admtxt',0);
				}
			});
		}
		var list = function(){
			var bindHandlers = function(){
				o.tinyscrollbar_ext({
					main : ".tinycanvas",
					fill : ".list_t"
				})
			}
			$("div#seminar_p div#panel_r").load("/desktop/seminar_p_list",function(){
				bindHandlers();
			})
		}
		var addseminar = function(){
			var bindHandlers = function(){
				o.simple_drop_down();
				o.tinyscrollbar_ext({
					main: '.tinycanvas',
					fill: '.s_grid_con'
				})
			}
			$("div#seminar_p div#panel_r").load("/desktop/seminar_p_add",function(){
				bindHandlers();
			})
		}
		if(!o.desktopData[o.currentface]){
			$(o.contentHolder).empty().load("/desktop/"+target,function(){
				list();
				bindHandlers();
			});
		}else{
			$(o.contentHolder).html(o.desktopData[o.currentface]);
			list();
			bindHandlers();
		}
	}
	this.initializeResearchDomain = function(target){
		o.currenthtml = target;
		o.currentface = "research_d";
		var bindHandlers = function(){
			$('.s_menu a').on({
				click: function(){
					if(!$(this).hasClass('active')){
						var tfunc = $(this).attr('href');
						switch(tfunc){
							case 'list':
								list();
							break;
							case 'add':
								add_this();
							break;
						}
						$('.s_menu a').removeClass('thmc1 thmtxt active');
						$(this).addClass('thmc1 thmtxt active');
					}
				},
				mouseenter: function(){
					if(!$(this).hasClass('active')){
						$(this).switchClass('admtxt','thmc1 thmtxt',0);
					}
				},
				mouseleave: function(){
					var t = $(this).hasClass('active') ? '' : 'thmc1 thmtxt';
					$(this).switchClass(t,'admtxt',0);
				}
			});
		}
		var list = function(){
			var bindHandlers = function(){
				o.tinyscrollbar_ext({
					main : ".tinycanvas",
					fill : ".list_t"
				})
			}
			$("div#research_d div#panel_r").load("/desktop/research_d_list",function(){
				bindHandlers();
			})
		}
		var add_this = function(){
			var bindHandlers = function(){
				o.simple_drop_down();
				o.tinyscrollbar_ext({
					main: '.tinycanvas',
					fill: '.s_grid_con'
				})
			}
			$("div#research_d div#panel_r").load("/desktop/research_d_add",function(){
				bindHandlers();
			})
		}
		if(!o.desktopData[o.currentface]){
			$(o.contentHolder).empty().load("/desktop/"+target,function(){
				list();
				bindHandlers();
			});
		}else{
			$(o.contentHolder).html(o.desktopData[o.currentface]);
			list();
			bindHandlers();
		}
	}
	this.initializeResearchProject = function(target){
		o.currenthtml = target;
		o.currentface = "research_p";
		var bindHandlers = function(){
			$('.s_menu a').on({
				click: function(){
					if(!$(this).hasClass('active')){
						var tfunc = $(this).attr('href');
						switch(tfunc){
							case 'list':
								list();
							break;
							case 'add':
								add_this();
							break;
						}
						$('.s_menu a').removeClass('thmc1 thmtxt active');
						$(this).addClass('thmc1 thmtxt active');
					}
				},
				mouseenter: function(){
					if(!$(this).hasClass('active')){
						$(this).switchClass('admtxt','thmc1 thmtxt',0);
					}
				},
				mouseleave: function(){
					var t = $(this).hasClass('active') ? '' : 'thmc1 thmtxt';
					$(this).switchClass(t,'admtxt',0);
				}
			});
		}
		var list = function(){
			var bindHandlers = function(){
				o.tinyscrollbar_ext({
					main : ".tinycanvas",
					fill : ".list_t"
				})
			}
			$("div#research_p div#panel_r").load("/desktop/research_p_list",function(){
				bindHandlers();
			})
		}
		var add_this = function(){
			var bindHandlers = function(){
				o.simple_drop_down();
				o.tinyscrollbar_ext({
					main: '.tinycanvas',
					fill: '.s_grid_con'
				})
			}
			$("div#research_p div#panel_r").load("/desktop/research_p_add",function(){
				bindHandlers();
			})
		}
		if(!o.desktopData[o.currentface]){
			$(o.contentHolder).empty().load("/desktop/"+target,function(){
				list();
				bindHandlers();
			});
		}else{
			$(o.contentHolder).html(o.desktopData[o.currentface]);
			list();
			bindHandlers();
		}
	}
	this.loadWallpaper = function(wallpaper){  // this is to load new wallpaper 
		if(!wallpaper)wallpapernm = o.themesettings.background;else wallpapernm = wallpaper
		var ww = $(window).width();
		var wh = $(window).height();
		if(!wallpaper)
			$("img#thmbackground").attr({"src":"/"+o.themefolder+"/"+o.theme+"/images/"+wallpapernm,"width":ww}).css({"position":"fixed","top":"0px","left":"0px","z-index":"-1","height":"auto"});
		else
			$("img#thmbackground").attr({"src":o.wallpaperPath+wallpaper,"width":ww}).css({"position":"fixed","top":"0px","left":"0px","z-index":"-1","height":"auto"});
			
		$("div#bgover").css({"position":"fixed","top":"0px","left":"0px","z-index":"-1","width":ww,"height":wh});
	};
	
	this.loadIconCache = function(){  // this function load or refresh icon cache for the theme
		var imgs = $("ul.docklist img");
		$.each(imgs,function(){
			var setting_name = $(this).attr("id").replace("_icon","");
			$(this).attr("src","/"+o.themefolder+"/"+o.theme+"/images/"+o.themesettings.icons[setting_name])
		})
	};
	this.initializeWidgets = function(){ // this function will initialize all the widgets in the desktop
		var elements = $("#group_wrapper li.element");
		$.each(elements,function(){
			var widget = $(this);
			if(widget.attr("data-category")=="widget"){
				var widgename = widget.attr("data-content");
				$.getScript("/desktop_widgets/"+widgename+"/"+widgename+".js",function(){
					widget.find("div.appholder").load("/desktop_widgets/"+widgename+"/index.html.erb");
				});
			//	$(this).find("div.appholder").append( $('