Orbit/app/assets/javascripts/orbitdesktop.js

1754 lines
70 KiB
JavaScript
Executable File

// JavaScript Document
//harry
//Inititialize function will initialize desktop
//callback-method will be called after desktop controlled ajax call
//container=true is the area where the view will be loaded
//load = true is used to load the submenu item by default
//response-type = "json"|"script"|"xml|html" default is json
//autocomplete-list = "listname" an array from which autocomplete will be attached to its respective input or textarea
//ajax-remote="get/delete/post/false" this will automatically bind the <a> with remote ajax call. By default if the resposne is html, it ll be inserted in container=true, false option will not make any calls and also stop page refresh
// content-holder = "jquery dom", the returned html of server will be put inside the dom mentioned in content-holder of a tag. this can be used in a tags as attributes
//confirm-message ="Some message", this will prompt user with a confirm box and show the message before ajax call is made.
//"toggle-onclick" = "classes to get toggle" this will toggle classes on toggle when a tags are clicked.
//"delete-item" = "true" this will remove its respective item from the list.
//"pagination-link" = "url" this url will be used for pagination.. this will override last link url.
//"pagination-var" = "variable to send paramater with url for pagination" this will enable pagination with this attribute for that view.
//for layout tinyscrollbar
//content-layout="datalist|column|simple" datalist is for data list from database.. column is usually for forms and some other pages.. simple is without any columns, the page will be displayed as it is.. base width will be considered the default width for tinyscrollbar
//base-width="300" this is the basic width of each column and in case of simple layout it ll be the final width
//per-column="5" this option is only for datalist layout.. this ll specify number of enteries per column.. default is 4
//column="true" this option is only for column layout... the columns will be formed on this column=true attribute and it should be a div
//item=true this attribute should be present in the li tag. li with this attribute are considered as a separate item.
$.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;
};
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: (data.results[0] || '')
// YQL screws with <script>s
// Get rid of them
.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
var orbitDesktop = function(dom){
orbitDesktopAPI.apply(this);
// o = this;
this.contentHolder = dom;
this.themesettings = "";
this.theme = "4f8d3f493b67fcd05f086359";
this.transitionTime = 500;
this.currenthtml = "home";
this.currentface = "home";
this.desktopData = {};
this.tp = "";
this.sectionList;
this.data_method;
this.gridvar = null;
this.lastlink= null;
this.tinyscrollbar = null;
this.locationdata = {};
this.initialize = function(){
var theme = o.theme;
var custom = false;
o.getlocation();
$.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( $('<link rel="stylesheet" id="dyn_css" type="text/css" />').attr('href', "/"+o.themefolder+"/"+theme+"/css/"+ts.css));
if(custom){
$("head").find("#dyn_css").remove();
$("head").append(customtheme);
}
$(document).ready(function(){
o.loadWallpaper(customwallpaper);
o.bindDesktopEvents();
o.loadIconCache();
o.getlocation();
var custom_load = window.location.hash;
if(!custom_load){
$(o.contentHolder).empty().load("/desktop/desktop",function(){
o.desktopData["d_desktop"] = "";
o.initializeDesktop("d_desktop","",false);
})
}else{
o.customPage(custom_load);
}
});
})
}
}
this.customPage = function(customload){
customload = customload.replace("#","");
if(customload.search("-") != -1){
customload = customload.split("-");
o.menu_item($(".docklist a[custom-load="+customload[0]+"]"),true,customload[1]);
}else{
o.menu_item($(".docklist a[custom-load="+customload+"]"),true);
}
}
this.changeTheme = function(theme){ // this function is used for changing theme
o.theme = theme;
$.getJSON("/"+o.themefolder+"/"+theme+"/settings/"+theme+".json",function(ts){
o.themesettings = eval(ts);
$('head').find("#dyn_css").remove();
$('head').append( $('<link rel="stylesheet" id="dyn_css" type="text/css" />').attr('href', "/"+o.themefolder+"/"+theme+"/css/"+ts.css));
o.loadWallpaper();
o.loadIconCache();
})
};
this.getlocation = function(){
var locationSuccess = function(pos){
o.locationdata.lat = pos.coords.latitude;
o.locationdata.lng = pos.coords.longitude;
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?latlng="+o.locationdata.lat+","+o.locationdata.lng+"&sensor=true",function(data){
$.each(data.results[0].address_components,function(i,val){
o.locationdata[val.types[0]] = val.long_name;
})
o.locationdata.formatted_address = data.results[0].formatted_address;
})
}
var locationError = function(){
o.notify("Unable to find your location!","alert");
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess,locationError);
}
else{
o.notify("Your browser does not support Geolocation!","alert");
}
}
this.bindDesktopEvents = function(){ //this function will bind the global handlers to thd desktop, for example doc
$(".docklist a").click(function(){
o.menu_item($(this));
return false;
})
$('body').on({
click: function(){
if(!$(this).hasClass('active')){
o.sub_menu_item($(this));
}
return false;
},
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);
}
},'*[content-type=menu] a');
$("body").on("submit","form[form-type=ajax_form]",function(){
var callback_method = $(this).attr("callback-method");
var dt = null;
dt = $(this).attr("response-type");
if(dt == null){
dt = "json";
}
var options = {
dataType : dt,
success:function(responseText, statusText, xhr, $form){
if(typeof callback_method != "undefined"){
if(callback_method != ""){
window.o[o.data_method][callback_method](responseText,statusText,xhr,$form);
}
}
},
error:function(){
o.notify("Please try again later!","imp");
}
}
$(this).ajaxSubmit(options);
return false;
})
$("body").on("click","*[ajax-remote]",function(){
var $e = $(this);
var t = $e.attr("ajax-remote");
var classes_to_toggle = $e.attr("toggle-onclick");
var exe = $e.attr("callback-method"); // (typeof $e.attr("callback-method") == "function"? $e.attr("callback-method") : "");
if(classes_to_toggle){
$e.toggleClass(classes_to_toggle);
}
if(t == "false"){
if(exe){
window.o[o.data_method][exe](null,$e);
}
return false;
}
var ca = $e.attr("content-holder");
var a = function(){
$.ajax({
type : t,
url : $e.attr("href"),
success : function(data){
if(typeof data == "string"){
if(ca)
$(ca).html(data);
else{
o.layout_data(data);
// $("div[container=true]").html(data);
}
}
if(exe)
window.o[o.data_method][exe](data,$e);
if(t == "delete"){
if($e.attr("delete-item")=="true"){
var li_to_delete = $e.parentsUntil("li[item=true]").find("li[item=true]");
li_to_delete.slideUp();
}
}
}
});
}
if($e.attr("confirm-message")){
o.confirm({
buttons : ["Yes","No"],
highlighted : 2,
message : $e.attr("confirm-message")
},function(value){
if(value){
a();
}
})
}else{
a();
}
return false;
})
$(window).resize(function(){
var ww = $(window).width();
$("img#thmbackground").attr({"width":ww});
if( $('.tinycanvas').length > 0 ){ $('.tinycanvas').tinyscrollbar_update('relative'); }
if($(o.contentHolder).find("div.app_frame").length > 0){
$(o.contentHolder).find("div.app_frame").each(function(){
var app_holder_height = $(this).height() - 72;
var app_holder_width = $(this).width();
$(this).find("div.app_holder").height(app_holder_height);
$(this).find("div.app_holder iframe").attr({"height":app_holder_height,"width":app_holder_width});
})
}
});
var $widget_fn = $('.widget_fn'),$fn_des = $('.fn_des');
$widget_fn.hover(function(){
var fn_name = $(this).find('img').attr('alt'),nth = $(this).parents('.d_cate').index(),des_left = $('.dock_child').eq(nth).width();
$(this).addClass('thmc1');
$fn_des.text(fn_name).css({'top':nth * 60,'left': des_left + 60}).stop(true, true).fadeIn();
},function(){
$(this).removeClass('thmc1');
$fn_des.stop(true, true).fadeOut();
});
var split = function( val ) {
return val.split( /,\s*/ );
}
var extractLast = function( term ) {
return split( term ).pop();
}
var autocompleteListName = null;
$("body").on("keydown","*[autocomplete-list]", function( event ) {
autocompleteListName = $(this).attr("autocomplete-list");
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
window.o[o.data_method][autocompleteListName], extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
})
})
};
this.layout_data = function(h){
var $e;
var column_container,layout, base_width , no_of_entries = 0, pagination_link , pagination_variable, gutter, total_width;
o.paging = true;
gutter = (!isNaN(gutter)) ? gutter : 12;
this.layout_data.generate_layout_html = function(l){
$e = $("<div></div>");
$e.html(l);
column_container = $e.find("div.overview");
layout = column_container.attr("content-layout"), base_width = parseInt(column_container.attr("base-width")), no_of_entries,total_columns=0, pagination_link = column_container.attr("pagination-link"), pagination_variable = column_container.attr("pagination-var");
var temp_div = $("<div></div>");
var entries = [];
switch (layout){
case "simple":
total_columns++;
temp_div.append(column_container.html());
total_width = "auto";
break;
case "datalist":
no_of_entries = (typeof column_container.attr("per-column") != "undefined"? parseInt(column_container.attr("per-column")) : 4);
var height_percentage = 100/no_of_entries;
entries = column_container.find("li[item=true]"),x = 0;
if(entries.length != 0){
entries.each(function(i,li){
if(x == 0){
column = $("<div class='column type_datalist' style='width:"+base_width+"px;margin-right:"+gutter+"px;padding-right:"+gutter+"px;'><ul></ul></div");
total_columns++;
}
$(li).wrapInner('<div class="inner"/>').addClass("datalist_item").height(height_percentage+"%");
column.find("ul").eq(0).append(li);
x++;
if(x == no_of_entries){
x = 0;
temp_div.append(column);
}
})
if(x != 0){
temp_div.append(column);
}
}
total_width = (!isNaN(base_width)) ? (base_width + gutter*2 +1) * total_columns : null;
break;
case "column":
entries = column_container.find("div[column=true]"),x = 0,column;
if(entries.length!=0){
entries.each(function(i,ul){
column = $("<div class='column type_column' style='width:"+base_width+"px;margin-right:"+gutter+"px;padding-right:"+gutter+"px;'></div");
total_columns++;
column.append(ul);
x++;
temp_div.append(column);
})
total_width = (!isNaN(base_width)) ? (base_width + gutter*2 +1) * total_columns : null;
}
break;
default:
break;
}
// total_width = (!isNaN(base_width) ? ( base_width + 12 ) * total_columns : null);
return {"markup":temp_div.html(),"width":total_width,"total":entries.length};
}
$("div[container=true]").html(h).find("div.overview").wrap('<div class="tinycanvas"><div class="viewport"></div></div>');
$("div[container=true]").find("div.tinycanvas").prepend('<div class="scrollbar sb_h vp"><div class="track"><div class="thumb thmc2"><div class="end"></div></div></div></div>');
var f = o.layout_data.generate_layout_html(h)
$("div[container=true] div.overview").html(f.markup);
var settings = {main : ".tinycanvas"};
var tsettings = {};
if(f.width){
settings.fill = f.width;
}
if(pagination_variable){
var page_no = 1;
tsettings.onMove = function(x){
if(x < 50){
if(!pagination_link)
pagination_link = o.lastlink;
if(o.paging){
page_no++;
o.paging = false;
o.pagination(pagination_link,pagination_variable,page_no);
}
}
}
}
o.tinyscrollbar_ext(settings,tsettings);
}
this.paging = true;
this.pagination = function(link,variable,page_no){
var retvalue = null;
$.ajax({
url : link + "?"+variable + "=" + page_no,
type : "get",
success : function(html){
var f = o.layout_data.generate_layout_html(html);
// console.log(f.total)
if(f.total > 0){
$("div[container=true] div.overview").append(f.markup);
if(f.width){
var w = $("div[container=true] div.overview").width();
$("div[container=true] div.overview").width(w+f.width);
}
o.tinyscrollbar.tinyscrollbar_update("relative");
o.paging = true;
}else{o.paging = false;}
}
})
}
this.insert_new_column = function(index){
var column_container = $("div[container=true] div.overview"),layout = column_container.attr("content-layout"),base_width = parseInt(column_container.attr("base-width")),column;
var i = (index == 0? 0 : index-1);
var previous_column = column_container.find(".column").eq(i);
if(previous_column.length == 0)return false;
switch(layout){
case "datalist":
column = $("<div class='column type_column' style='width:"+base_width+"px'></div");
break;
case "column":
column = $("<div class='column type_column' style='width:"+base_width+"px'></div");
break;
default:
return false;
break;
}
if(index == 0){
column.insertBefore(previous_column)
}else{
column.insertAfter(previous_column);
}
var total_columns = column_container.find(".column").length;
o.tinyscrollbar_ext({
main : ".tinycanvas",
fill : base_width * total_columns
})
return column;
}
this.remove_column = function(index){
var column_container = $("div[container=true] div.overview"),layout = column_container.attr("content-layout"),column = column_container.find(".column").eq(index),base_width = parseInt(column_container.attr("base-width"));
if(column.length == 0)return false;
switch(layout){
case "datalist":
case "column":
break;
default:
return false;
break;
}
column.remove();
var total_columns = column_container.find(".column").length;
o.tinyscrollbar_ext({
main : ".tinycanvas",
fill : base_width * total_columns
})
return column;
}
this.menu_item = function(dom,customload,submenuitem){
if(!customload)customload=false;
var target = dom.attr("id");
var url = dom.attr("href");
if(!url)return false;
o.lastlink = url;
o.data_method = dom.attr("callback-method");
if(o.currenthtml!=target){
if(o.desktopData[o.currentface] == "undefined")
o.desktopData[o.currentface] = "";
o.desktopData[o.currentface] = $(o.contentHolder).html();
if(customload){
$(o.contentHolder).html("<div id='content'></div>");
}
$("#content").hide("drop",o.transitionTime,function(){
o.currenthtml = target;
o.currentface = target;
var cache = false;
if(!o.desktopData[o.currentface]){
$(o.contentHolder).empty().load(url,function(data){
if(typeof o.data_method != "undefined"){
if(o.data_method != "")
window.o[o.data_method](target,url,cache);
}
try{
if(!customload)
o.sub_menu_item($(o.contentHolder).find("*[content-type=menu] a[load=true]"),data);
else{
if(submenuitem)
o.sub_menu_item($(o.contentHolder).find("*[content-type=menu] a[custom-load="+submenuitem+"]"));
else
o.sub_menu_item($(o.contentHolder).find("*[content-type=menu] a[load=true]"),data);
}
}catch(EX){}
})
}else{
$(o.contentHolder).html(o.desktopData[o.currentface]);
try{
if(!customload)
o.sub_menu_item($(o.contentHolder).find("*[content-type=menu] a[load=true]"),data);
else{
if(submenuitem)
o.sub_menu_item($(o.contentHolder).find("*[content-type=menu] a[custom-load="+submenuitem+"]"));
else
o.sub_menu_item($(o.contentHolder).find("*[content-type=menu] a[load=true]"),data);
}
}catch(EX){}
cache = true;
if(typeof o.data_method != "undefined"){
if(o.data_method != "")
window.o[o.data_method](target,url,cache);
}
}
});
}
}
this.sub_menu_item = function(dom,data){
var sub_data_method = dom.attr('callback-method');
if(sub_data_method){
o.lastlink = dom.attr("href");
$.ajax({
url : dom.attr("href"),
type : "get",
success : function(data){
o.layout_data(data);
if(typeof o.data_method != "undefined"){
if(o.data_method != ""){
if(typeof sub_data_method != "undefined"){
if(sub_data_method != ""){
window.o[o.data_method][sub_data_method]();
}
}
}
}
}
})
o.highlight_sub_menu_item(dom);
}
if(dom.length == 0)
o.layout_data(data);
// $('*[content-type=menu] a').removeClass('thmc1 thmtxt active');
// dom.addClass('thmc1 thmtxt active');
}
this.highlight_sub_menu_item = function(no){
$('*[content-type=menu] a').removeClass('thmc1 thmtxt active');
var dom;
if(typeof no == "number"){
dom = $('*[content-type=menu] a').eq(no);
dom.addClass('thmc1 thmtxt active');
}else if(typeof no == "object"){
dom = no;
dom.addClass('thmc1 thmtxt active');
}
return dom;
}
this.initializeDesktop = function(target,url,cache){ //this is for initializing main desktops that are sections and tiles
if(!target)target = "home";
var bindHandlers = function(){ // this function will bind all the handlers in the desktop
// var groupWrapperWidth = 0;
// $("div#desktop .group").each(function(){groupWrapperWidth+=$(this).outerWidth(true);});
// var grps = new Array;
// $("div#desktop #group_wrapper").css("width",groupWrapperWidth);
// var first = true;
// $("div#desktop .g_col").sortable({
// connectWith: ".g_col",
// tolerance: 'pointer' ,
// revert: 300,
// containment: '#group_wrapper',
// helper: 'clone',
// stop:function(){
// first = true;
// var grpwidth = 0;
// for(i in grps){
// var grp = grps[i];
// if(grp.find(".element").length == 0){
// grp.animate({"width":"0px"},500,function(){$(this).remove();});
// grpwidth+=225;
// }
// }
// grps = [];
// $("#group_wrapper").width($("#group_wrapper").width()-grpwidth);
// },
// start:function(){
// $("#group_wrapper").find("div.group").each(function(i,par){
// var nextnumber = $(this).find("ul").length;
// $newcol = $('<ul class="g_col g_col_w2 col'+nextnumber+' ui-sortable">');
// $(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');
// }
// }
// });
var dragged = null,draggable,lastpos = [];
o.gridvar = $(".grid ul").find("> li ").mousedown(function(e){
!draggable;
dragged = $(this);
lastpos = [];
$(".grid ul li").each(function(){
lastpos.push({"col":$(this).attr("data-col"),"row":$(this).attr("data-row")})
})
}).end()
.gridster({
widget_margins: [6, 6],
widget_base_dimensions: [120, 120],
// avoid_overlapped_widgets: true,
serialize_params: function($w, wgd) { return { col: wgd.col, row: wgd.row, id: $w.data("id") } },
draggable : {
start : function(event, ui){
dragged.addClass("noClick");
},
stop: function(event, ui){
// var widgetchanged_col = dragged.attr("data-col");
// var total = 0;
// // console.log(widgetchanged.col);
// // console.log(o.gridvar.serialize_changed());
// $(".grid ul li[data-col="+widgetchanged_col+"]").each(function(i,w){
// var size = parseInt($(this).attr("data-sizey"));
// if(!isNaN(size)){
// total += size;
// }
// })
// // other way to calculate the overflow is by top > height of div
// if(total>totaltiles_in_a_row){
// revertbacktiles();
// }else{
// console.log(widgetchanged_col-1);
// $(".grid ul li[data-col="+(widgetchanged_col-1)+"]").each(function(i,w){
// var sizey = parseInt($(this).attr("data-sizey"));
// var sizex = parseInt($(this).attr("data-sizex"));
// if(sizey==1){
// sizex = sizex - 1;
// }
// console.log(sizex);
// if(!isNaN(sizex)){
// total += sizex;
// }
// })
// if(total>totaltiles_in_a_row){
// revertbacktiles();
// }
// }
for (var i = 1; i <= 30; i++) {
// var celement = $(".grid ul .widget[data-col="+i+"]:last");
$(".grid ul .widget[data-col="+i+"]").each(function(){
var pos = $(this).position();
if(pos){
if((pos.top + $(this).height() + 6) > 550){
revertbacktiles();
}
}
})
}
var newpos = o.gridvar.serialize();
console.log(newpos);
$.post("/desktop/newpositions",{"newpositions":newpos});
}
}
}).data('gridster');
var revertbacktiles = function(){
lastpos.push({"col":"","row":""});
$(".grid ul li").each(function(i){
$(this).attr({"data-col":lastpos[i].col,"data-row":lastpos[i].row});
})
}
var remove_empty_columns = function(){
for (var i = 1; i <= 30; i++) {
// var celement = $(".grid ul .widget[data-col="+i+"]:last");
$(".grid ul .widget[data-col="+i+"]").each(function(){
})
break;
}
}
o.simple_drop_down();
o.tinyscrollbar_ext({
main: '.tinycanvas'
})
$("li.app[data-category=app]").click(function(){
if(!$(this).hasClass("noClick")){
var url = $(this).find("a").data("url");
var app = $(this);
o.appWindow({
"appid" : app.data("id"),
"title" : app.data("title"),
"url" : url
})
}
dragged.removeClass("noClick");
})
// $("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(tiles){
// tiles.sort(o.sortJSON("position",true,parseInt));
var tilecolors = o.themesettings.tilecolor;
var totaltiles_in_a_row = 4;
var opacity = ["op07","op08","op09",""];
var row = 0,col = 1,x = 1,y = 1,total_x = 0,prev_y = 0;
var $group = $('<div class="grid gridster"></div>');
var $ul = $('<ul style="margin: -6px 0 0 -6px;"></ul>');
$.each(tiles,function(i,tile){
var shape = tile.shape.split(" ");
// if(tile.title == "Weather")console.log("Big - row : " + tile.row + ", col : "+ tile.column);
// if(tile.title == "Google Scholar")console.log("Scholar - row : " + tile.row + ", col : "+ tile.column);
// if(total_x % 2 != 0)
// row = row - y;
// if(i == 7)tile.row = null;
if(tile.row){
row = tile.row;
col = tile.column;
x = parseInt(shape[0].substr(1,1));
y = parseInt(shape[1].substr(1,1));
}else{
console.log(row + " : " + col);
x = parseInt(shape[0].substr(1,1));
if(total_x % 2 == 0){
row = row + y;
}else if(x == 1){
col++;
}
y = parseInt(shape[1].substr(1,1));
total_x = total_x + ( x * y );
prev_y = y;
if(total_x > 8){
row = 1;
total_x = 0;
col++;
}
}
var tilecolor = tilecolors[Math.floor(Math.random()*tilecolors.length)];
var op = opacity[Math.floor(Math.random()*opacity.length)];
var f = (tile.fullsize?"fullsize":null);
if(tile.data_category == "app")
$li = $('<li data-id="'+tile.id+'" class="app" data-row="'+row+'" data-col="'+col+'" data-sizex="'+x+'" data-sizey="'+y+'" data-title="'+tile.title+'" data-category="'+tile.data_category+'" data-content="'+tile.data_content+'"><span class="tile '+tilecolor+' '+op+'"></span><a href="'+tile.data_content+'" class="appicon" onclick="return false;" data-url="'+tile.link+'"><img src="'+o.iconPath+tile.data_content+'.png" alt="" ></a><h1 class="appname thmtxt">'+tile.title+'</h1></li>');
else
$li = $('<li data-id="'+tile.id+'" class="widget '+f+'" data-row="'+row+'" data-col="'+col+'" data-sizex="'+x+'" data-sizey="'+y+'" data-category="'+tile.data_category+'" data-content="'+tile.data_content+'" js-link="'+tile.js[0].url+'" css-link="'+tile.css.url+'"><span class="tile '+tilecolor+' '+op+'"></span><div class="appholder"><div class="thmtxt o-loading"><i class="icon-spinning icon-spinner"></i> Loading</div></div><h1 class="appname thmtxt">'+tile.title+'</h1></li>');
$ul.append($li);
})
$group.append($ul);
$("div#desktop div#group_wrapper").append($group);
bindHandlers();
o.initializeWidgets();
})
// 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 = $('<div class="group"><ul class="grp ui-sortable"></ul></div>'),
// var colindex = 0,
// $group = $('<div class="group"></div>'),
// $col = $('<ul class="g_col g_col_w2 col'+ colindex +'"/>'),
// $li,
// bdsum = 0,
// bwsum = 0,
// bhsum = 0,
// small = 0,
// single = false;
// $group.append($col);
// for(j=0;j<group.length;j++){
// var tile = group[j];
// var brick = tile.shape.replace(' holder_f','').split(' '),
// bw = parseInt(brick[0].substr(1)),
// bh = parseInt(brick[1].substr(1)),
// bd = bw * bh;
// if(bh==1 && bw==1){
// small++;
// }else if(bh!=1 && bw!=1){
// single = true;
// }
// if(small==2){
// small=0;
// single=false;
// }else if(small==1 && single==true){
// bh++;
// small=0;
// single=false;
// }else{small=0;single=false;}
// bdsum+=bd;
// bwsum+=bw;
// bhsum+=bh;
// if(bdsum > 8 || bhsum > 6){
// bdsum = 0, bhsum = 0, colindex++,j--;
// $group.append('<ul class="g_col g_col_w2 col'+ colindex +'"/>');
// }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 = $('<li data-id="'+tile.id+'" class="element '+tile.shape+' hp vp" data-category="'+tile.data_category+'" data-content="'+tile.data_content+'" ><span class="tile '+tilecolor+' '+op+'"></span><a href="'+tile.data_content+'" class="appicon" onclick="return false;"><img src="'+o.iconPath+tile.data_content+'.png" alt="" ></a><h1 class="appname thmtxt">'+tile.title+'</h1></li>');
// else
// $li = $('<li data-id="'+tile.id+'" class="element '+tile.shape+' hp vp" data-category="'+tile.data_category+'" data-content="'+tile.data_content+'" js-link="'+tile.js[0].url+'" css-link="'+tile.css.url+'"><span class="tile '+tilecolor+' '+op+'"></span><h1 class="appname thmtxt">'+tile.title+'</h1><div class="appholder">Loading...</div></li>');
// $group.find('.col'+colindex).append($li);
// }
// }
// $("div#desktop div#group_wrapper").append($group);
// })
// })
}
var loadSectionList = function(){ //This will load the section list from the db
$.getJSON("/desktop/getsectionlist",{desktopid:o.desktopId},function(sectionlist){
o.sectionList = eval(sectionlist);
$.each(sectionlist,function(i,section){
var tempstyle="";
if(i==0){
tempstyle = "style='display:none;'";
$("#desktop #section_heading").text(section.name);
}
$("div#desktop ul#section_list").append($('<li class="section_name" '+tempstyle+'><a class="admtxt hp w2 hh1" onclick="return false;" href="'+section._id+'" >'+section.name+'</a></li>'));
})
bindSecondaryHandlers();
})
}
var bindSecondaryHandlers = function(){ //This is the secondary bind handler function which is used to bind events which are repeatative
$("div#desktop ul#section_list li.section_name").click(function(){
$("div#desktop li.section_name").show();
$(this).hide();
$("#desktop #section_heading").text($(this).text());
o.sectionId = $(this).find("a").attr("href");
loadTiles(o.sectionId);
})
}
if(cache){
bindHandlers();
o.initializeWidgets();
bindSecondaryHandlers();
$("div#desktop ul#section_list").empty();
$.each(o.sectionList,function(i,section){
var tempstyle="";
if(section._id==o.sectionId){
tempstyle = "style='display:none;'";
$("div#desktop span#section_heading").text(section.name);
}
$("div#desktop ul#section_list").append($('<li class="section_name" '+tempstyle+'><a class="admtxt hp w2 hh1" onclick="return false;" href="'+section._id+'" >'+section.name+'</a></li>'));
})
bindSecondaryHandlers();
}else{
loadTiles(o.sectionId);
loadSectionList();
}
};
this.tempFunc = function(th){
$.post("desktop/twitter",function(){});
};
this.initializeAppSearch = function(target,url,cache){ //this is application search ie is app manager initialization
var searchArray,allApps;
var bindHandlers = function(){ // bind handler for app manager page
var gn = $('.g_col').length,
gw = $('.g_col').outerWidth(true);
$("#app_manager #group_wrapper").css("width",gn*gw);
// $("div#app_manager .group_search").css("width",$(window).width()-200);
//for textbox search
$("#app_manager #searchbox").focus(function(){$(this).val("");}).keyup(function(e){
if($(this).val()){
$("div#app_manager .search_result").empty();
$("div#app_manager #seperator").hide();
searchArray = $("div#app_manager .element:containsi("+$(this).val()+")");
if(searchArray.length>0){
$("div#app_manager #seperator").show();
var i = 0;
var $column;
searchArray.each(function(){
i++;
if(i == 1){
$column = $("<div style='width:120px; float:left;'></div>");
}
var $newelement = $('<div class="search element w1 h1 hp vp thmc2" data-category="desktop">'+$(this).html()+'</div>');
$column.append($newelement);
if(i == 4){
$("div#app_manager .search_result").append($column);
i = 0;
}
})
if(i != 0){
$("div#app_manager .search_result").append($column);
}
}
}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('<div class="g_col g_col_w1 col'+ colindex +'"/>');
$.each(allApps,function(i,app){
count++;
if( count > 4 ){
count = 1, colindex+=1;
$('#app_list').append('<div class="g_col g_col_w1 col'+ colindex +'"/>');
$('.g_col.col'+ colindex).append(app);
} else {
$('.g_col.col'+ colindex).append(app);
}
})
return false;
})
}
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('<div class="g_col g_col_w1 col'+ colindex +'"/>');
$.each(appss,function(i,apps){
$.each(apps,function(i,app){
var $app;
count++;
$app = $('<div class="element w1 h1 hp vp thmc2" data-category="'+app.data_category+'" data-content="'+app.data_content+'"><span class="tile thmc2"></span><a href="'+app._id+'" class="appicon"><img src="'+o.iconPath+app.data_content+'.png" alt="" onclick="return false;"></a><h1 class="appname thmtxt">'+app.title+'</h1></div>');
if( count > 4 ){
count = 1, colindex+=1;
$('#app_list').append('<div class="g_col g_col_w1 col'+ colindex +'"/>');
$('.g_col.col'+ colindex).append($app);
} else {
$('.g_col.col'+ colindex).append($app);
}
})
})
bindHandlers();
})
}
if(cache)
bindHandlers();
else
loadApps();
};
this.initializeSectionsManager = function(target,url,cache){ // this is init function for section manager
var elementParent,element,slabel;
var bindHandlers = function(){ // this is bind handler for section manager page
var groupWrapperWidth = 0;
$("div#sections .group").each(function(){groupWrapperWidth+=$(this).width();})
groupWrapperWidth+=200;
groupWrapperHeight = $(".group").height() + 20;
$("#group_wrapper").width(groupWrapperWidth);
var sortingoptions = {
start:function(){
slabel = $(this).parent().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 #group_wrapper .appgroup").sortable(sortingoptions);
$("div#sections .section_label li:not(:nth-child(1))").droppable({
drop:function(event, ui){
elementParent = ui.draggable.parents('.group');
elementParentUl = ui.draggable.parents(".appgroup");
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(){
var newul = false;
if($list.find("ul").length == 0){
$list.append(('<ul class="appgroup w1" ></ul>'));
newul = true;
}else if($list.find("ul:eq(0) li").length == 7){
$list.append(('<ul class="appgroup w1" ></ul>'));
newul = true;
}
$(this).appendTo($list.find("ul:last")).fadeIn();
var next_group = elementParent.find(".grp ul").eq(elementParentUl.index() + 1);
if(elementParentUl.index() == 0){
if(elementParentUl.find("li").length < 7){
var element_to_shift = next_group.find("li").eq(0);
if(element_to_shift.length != 0){
elementParentUl.append(element_to_shift);
}
}
}
if(next_group.find("li").length == 0){
next_group.remove();
}
if(elementParentUl.find("li").length == 0){
elementParentUl.remove();
}
if(elementParent.find(".grp ul").length == 0){
elementParent.find(".grp").addClass("no_app");
}else{
elementParent.find(".grp").removeClass("no_app");
}
if(newul){
$("div#sections #group_wrapper .appgroup").sortable(sortingoptions);
$list.removeClass("no_app");
}
});
$.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'
});
};
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 = $('<div class="group" id="'+o.sectionList[section]._id+'"><div class="section_label"><ul class="section_grp"></ul></div><div id="section'+(z+1)+'" class="grp no_app" style="min-width:120px;"></div></div>');
for(x=0;x<4;x++){
if(x==0){
$li = $('<li class="element w1 h1 hp vp thmtxt" data-content="'+o.sectionList[z]._id+'"><span class="tile thmc1"></span><span class="thmtxt">'+o.sectionList[z].name+'</span></li>');
$group.find("ul.section_grp").append($li);
}
if(z!=x){
$lii = $('<li class="element w1 h1 hp vp thmtxt" style="display: none;" data-category="section'+(x+1)+'" data-content="'+o.sectionList[x]._id+'"><span class="tile thmc2 op06"></span><span class="thmtxt">'+o.sectionList[x].name+'</span></li>');
$group.find("ul.section_grp").append($lii);
}
}
z++;
$("div#group_wrapper").append($group);
}
var x = 0;
$.each(appss,function(i,apps){
x = 0;
$.each(apps,function(y,app){
x++;
if(x == 1){
$ul = $('<ul class="appgroup w1" ></ul>');
}
$li = $('<li class="element to_drop w1 hh2 hp vp" data-category="'+app.data_category+'" data-content="'+app.data_content+'" id="'+app._id+'"><div class="appicon"><img src="'+o.iconPath+app.data_content+'.png" class="" width="30" /></div><h1 class="appname thmtxth">'+app.title+'</h1></li>');
$ul.append($li);
if(x == 7){
$("div#group_wrapper div#section"+(i+1)).append($ul);
$("div#group_wrapper div#section"+(i+1)).removeClass("no_app")
x = 0;
}
})
if(x != 0){
$("div#group_wrapper div#section"+(i+1)).append($ul);
$("div#group_wrapper div#section"+(i+1)).removeClass("no_app")
}
})
bindHandlers();
})
}
if(cache)
bindHandlers();
else
loadApps();
};
this.initializeSettings = function(target,url,cache){ //this is to initialize setting page
this.initializeSettings.account = function(data){}
this.initializeSettings.passwordUpdate = function(data){
if(data.success){
o.notify(data.msg,"success");
}else{
o.notify(data.msg,"alert");
}
}
this.initializeSettings.sections = function(){ // this load section page in setting page
var bindHandlers = function(){ // binding handlers in section page
$("a#name_save_btn").click(function(){
var desktopnm = new Array;
$("#desktop_names input").each(function(){
desktopnm.push($(this).val());
})
$.post("/desktop/save_desktop_settings",{"save":"desktopnames","desktopid":o.desktopId,"desktopnms":desktopnm},function(result,status){
if(result[0].success=="true"){
o.notify("Names Saved!!","success",2);
}else
o.notify("Name saving failed!!","imp",2);
})
$.each(o.sectionList,function(i,sec){
sec.name = desktopnm[i];
})
})
}
$.getJSON("/desktop/get_desktop_settings",{"get":"sectionnames","desktopid":o.desktopId},function(sectionnames){
$("#desktop_names input").each(function(i){
$(this).val(sectionnames[i]);
})
bindHandlers();
})
}
this.initializeSettings.themes = function(){ // this opens themes page in setting page
var bindHandlers = function(){ // binding handlers in themes page
// live change theme
$(".theme_list > .ssl_item").click(function(){
o.changeTheme($(this).attr("id"));
// $(".theme_list > li").removeClass('thmc1').data('clicked',null).find('.theme_name').removeClass('thmtxt');
// $(this).addClass('thmc1').data('clicked',true).find('.theme_name').addClass('thmtxt');
$.post("/desktop/save_desktop_settings",{"save":"theme","desktopid":o.desktopId,"theme":$(this).attr("id")},function(result,status){
if(result[0].success=="true"){
o.notify("Theme Saved!!","success",2);
loadthmc();
} else {
o.notify("Theme saving failed!!","imp",2);
}
});
});
o.single_select();
o.simple_tab();
$('.color-picker').miniColors({
change:function(hex){
var changewhat = $(this).attr("for");
var previewarea = $("#theme_preview_area");
switch(changewhat){
case "thmtxt":
case "thmtxth":
previewarea.find("."+changewhat).css({"color":hex});
break;
case "g_sep":
previewarea.find("."+changewhat).css({"border-color":hex});
break;
case "background":
previewarea.css({"background-color":hex});
break;
default:
previewarea.find("."+changewhat).css({"background-color":hex});
break;
}
}
});
$("a#theme_submit").click(function(){
o.confirm({
message : "Are you sure that you want to save custom theme?",
highlighted : 1,
buttons : ["Yes","No"]
},function(reply){
if(reply){
var colors = new Array;
$("#color_input input").each(function(){
colors[$(this).attr("for")] = $(this).val();
})
var dhtml ="<style> .thmc1 { background: "+colors['thmc1']+"; }.thmc2 { background: "+colors['thmc2']+"; }.thmc3 { background: #FFFFFF; }.thmc4 { background: "+colors['thmc4']+"; }.thmtxt { color: "+colors['thmtxt']+"; }.thmtxth { color: "+colors['thmtxth']+"; }.g_sep { border-color: "+colors['g_sep']+";} body{background-color: "+colors['background']+"} </style>";
$("head").find("#dyn_css").remove();
$("head").append(dhtml);
$.post("/desktop/save_desktop_settings",{"save":"customtheme","desktopid":o.desktopId,"theme":dhtml},function(result,status){
if(result[0].success=="true")
o.notify("Custom theme saved!!","success",2);
else
o.notify("Custom theme saving failed!!","imp",2);
})
}
})
});
$(".stock_wallpaper .ssl_item").click(function(){
var wallpapername = $(this).find("img").attr("alt");
o.changeWallpaper(wallpapername);
})
}
var loadthmc = function(){ // a general function to load the themecolor in color selector
$('.color-picker').each(function(){
var cc = $(this).attr('for'), hex, color;
switch(cc){
case 'thmtxt':
case 'thmtxth':
hex = 'color';
break;
case 'g_sep':
hex = 'border-left-color';
break;
default:
hex = 'background-color';
break;
}
if(cc=="background")
color = $("#theme_preview_area").css("background-color");
else
color = $('#theme_preview_area .'+cc).css(hex);
$(this).miniColors("value", o.rgb2hex(color));
});
}
$.getJSON("/desktop/get_desktop_settings",{"get":"theme","desktopid":o.desktopId},function(theme){
$('#st1 .theme_list [id='+theme+']')
.addClass("thmc1 active", 300)
.find("span")
.addClass("thmtxt");
bindHandlers();
loadthmc();
})
}
this.initializeSettings.connection = function(){
var bindHandlers = function(){
$("#connection_setting ul a").click(function(){
var what = $(this).attr("for"),
type = $(this).attr("href"),
$ul = $("#"+type+"_connection"),
usernm = $ul.find("input[type=text]").val(),
pwd = $ul.find("input[type=password]").val();
switch(what){
case "save":
case "new":
if(usernm!="" && pwd!=""){
$ul.find("input[type=text]").replaceWith("<div class='c_info usrnm'>"+usernm+"</div>")
$ul.find("input[type=password]").replaceWith("<div class='c_info pwd'>&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;</div>");
$(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('<input type="text" value="'+un+'">');
$ul.find("div.pwd").replaceWith('<input type="password">');
$(this).text("Save").attr("for","save");
break;
case "delete":
var $this = $(this);
o.confirm({
message : "Are you sure that you want to remove this account?",
buttons : ["Yes","No"],
highlighted : 2
},function(reply){
if(reply){
$this.hide();
$ul.find("div.usrnm").replaceWith('<input type="text">');
$ul.find("div.pwd").replaceWith('<input type="password">');
$ul.find("span.c_status").text("No Connection").removeClass("c_status_on");
$this.parent().find("a[for=edit]").text("Connect").attr("for","new");
saveaccount("","",type,what);
}
})
break;
}
})
var $conlist = $('.s_form'),
conlist_w = $conlist.length * $conlist.outerWidth(true) + ($conlist.length - 1) * 25;
$('#connection_setting').width(conlist_w);
}
var saveaccount = function(usernm,pwd,type,what){
$.post("/desktop/save_account_info",{email:usernm,password:pwd,account:type,dowhat:what},function(result){
if(what!="delete"){
if(result[0].success=="true")
o.notify(type+" account connected!!","success",2);
else
o.notify(type+" account connection failed!!","imp",2);
}else{
if(result[0].success=="true")
o.notify(type+" account removed!!","success",2);
else
o.notify(type+" account removal failed!!","imp",2);
}
})
}
$.getJSON("/otheraccounts/getaccounts",function(accounts){
$.each(accounts,function(i,account){
$ul = $("#"+account.type+"_connection");
$ul.find("input[type=text]").replaceWith("<div class='c_info usrnm'>"+account.email+"</div>")
$ul.find("input[type=password]").replaceWith("<div class='c_info pwd'>&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;</div>");
$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();
})
}
};
this.initializeOrbitTimeline = function(target,url,cache){
var timeline = new orbitTimeline("#timeline");
timeline.initialize();
};
this.initializeAppstore = function(target,url,cache){
this.initializeAppstore.widgets = function(){
var bindHandlers = function(){
$("#widget_list a").click(function(){
var sectionid = $(this).attr("for");
var widgetid = $(this).parent().parent().attr("for");
switch($(this).attr("href")){
case "addthis":
$this = $(this);
o.confirm({
message: "Are you sure you want to add this widget?",
buttons: ['Yes','No'],
highlighted: 1
},function(reply){
if(reply){
$.post("desktop_appstore/widgets_settings",{section:sectionid, widget:widgetid, what:"add"},function(result){
if(result[0].success){
$this.attr("href","removethis");
$targetDom = $this.parent().parent().find("div.status");
$parentDom = $this.parent();
if($targetDom.find("a").length == 0)
$targetDom.html("Status : Installed on");
$targetDom.append(" ").append($this);
if($parentDom.find("a").length == 0)
$parentDom.empty();
o.desktopData["home"]="";
o.notify("Widget added.","success",2);
}else{
o.notify(result[0].error,"imp",2);
}
})
}
})
break;
case "removethis":
$this = $(this);
o.confirm({
message: "Are you sure you want to remove this widget?",
buttons: ['Yes','No'],
highlighted: 2
},function(reply){
if(reply){
$.post("desktop_appstore/widgets_settings",{section:sectionid, widget:widgetid, what:"remove"},function(result){
if(result[0].success){
$this.attr("href","addthis");
$targetDom = $this.parent().parent().find("div.not_status");
$parentDom = $this.parent();
if($targetDom.html()=="")
$targetDom.html("Install on");
$targetDom.append(" ").append($this);
if($parentDom.find("a").length == 0)
$parentDom.html("Status : Downloaded");
o.desktopData["home"]="";
o.notify("Widget removed.","success",2);
}
})
}
})
break;
}
return false;
});
o.tinyscrollbar_ext({
main: '.tinycanvas',
fill: '.list_t'
})
}
$.getJSON("/desktop_appstore/getuserwidgets",function(userwidgets){
var column = $('<div class="g_col list_t"><ul></ul></div>'),
counter = 1,
li;
$.each(userwidgets,function(i,widge){
if(!widge.status)widge.status = "Downloaded";
var brick = widge.shape.split(' '),
bw = parseInt(brick[0].substr(1)),
bh = parseInt(brick[1].substr(1)),
shp = bw+" X "+bh;
li = $('<li class="list_t_item" for="'+widge._id+'"><div class="list_t_title">'+widge.name+'</div><div class="list_t_des">Author : '+widge.author+'</div><div class="list_t_des">Shape : '+shp+'</div><div class="list_t_des status">Status : '+widge.status+'</div><div class="list_t_des not_status"></div></li>');
var cur_section_names = new Array();
var section_names = new Array();
var section_links = new Array();
if(widge.section){
var s_name_list = "";
$.each(widge.section,function(x,sec){
$.each(o.sectionList,function(j,s){
if(s._id==sec){
cur_section_names.push(s.name);
s_name_list+= "<a href='removethis' for='"+s._id+"' style='text-decoration:underline;'>"+s.name +"</a> ";
}
})
})
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+= "<a href='addthis' for='"+sec_link+"' style='text-decoration:underline;'>"+sec_name+"</a> ";
}
})
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 <a href='addthis' for='"+o.sectionList[0]._id+"' style='text-decoration:underline;'>"+o.sectionList[0].name+"</a> <a href='addthis' for='"+o.sectionList[1]._id+"' style='text-decoration:underline;'>"+o.sectionList[1].name+"</a> <a href='addthis' for='"+o.sectionList[2]._id+"' style='text-decoration:underline;'>"+o.sectionList[2].name+"</a> <a href='addthis' for='"+o.sectionList[3]._id+"' style='text-decoration:underline;'>"+o.sectionList[3].name)+"</a>";
}
//console.log(section_names);
column.find("ul").append(li);
if(counter%4==0){
$("#apps_store div#widget_list").append(column);
column = $('<div class="g_col list_t" style="width:350px;"><ul></ul></div>');
}
counter++;
})
$("#apps_store div#widget_list").append(column);
})
}
this.initializeAppstore.onlinestore = function(){
var bindHandlers = function(){
}
bindHandlers();
}
this.initializeAppstore.onlinestore();
bindHandlers();
}
this.loadWallpaper = function(wallpaper){ // this is to load new wallpaper
wallpapernm = (!wallpaper) ? o.themesettings.background : wallpaper;
if(!wallpaper){
$("img#thmbackground").attr("src","/"+o.themefolder+"/"+o.theme+"/images/"+wallpapernm);
} else {
$("img#thmbackground").attr("src",o.wallpaperPath+wallpaper);
}
};
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.widget");
$.each(elements,function(){
var widget = $(this);
if(widget.attr("data-category")=="widget"){
var widgename = widget.attr("data-content");
$.getScript(widget.attr("js-link"),function(){
widget.find("div.appholder").load(widget.attr("data-content"));
});
$(this).find("div.appholder").append( '<link rel="stylesheet" id="dyn_css" href="'+widget.attr("css-link")+'" type="text/css" />')
}
})
};
this.saveWallpaper = function(wallpaper){ // this function saves wallpaper in db
$.post("/desktop/save_desktop_settings",{"save":"wallpaper","wallpapernm":wallpaper,"desktopid":o.desktopId},function(result){
if(result[0].success=="true")
o.notify("Wallpaper saved!!","success",2);
else
o.notify("Wallpaper saving failed!!","imp",2);
})
};
this.tinyscrollbar_ext = function(target,tinysettings){
//main : dom on which tinyscrollbar has to be applied
//fill : number or object for width
//height : height for the target element
//tinysettings : tinyscrollbar settings
if(typeof target.main == "undefined"){
o.notify('Tinyscrollbar: target undefined','imp',2);
return;
}else{
target.main = $(target.main);
}
var settings = {"axis":"x"};
if(typeof tinysettings != "undefined")
$.map(tinysettings,function(val,i){ settings[i] = val })
var count,baseWidth,fillArray,pxs;
if( typeof target.fill == 'string' ){
// fillArray = target.main.find(target.fill);
// count = fillArray.length;
// baseWidth = $(target.fill).eq(1).outerWidth(true);
// target.main.find('.overview').width( baseWidth * count);
} else if( typeof target.fill == 'number' ){
target.main.find('.overview').width( target.fill );
} else if( typeof target.fill == 'undefined' ){
} else {
o.notify('Tinyscrollbar: setting width failed','imp',2);
}
if(target.height){
target.main.height(target.height);
}
o.tinyscrollbar = target.main.tinyscrollbar( settings );
};
this.simple_drop_down = function(){
// simple dropdown menu
if( !$('.sdm').children('.sdm_o').length > 0 ){
return;
} else {
$('.sdm').hover(function(){
$(this).stop(1,1).addClass('thmc2 thmtxt');
}, function(){
$(this).stop(1,1).removeClass('thmc2 thmtxt');
});
}
};
this.simple_tab = function(){
// tab
var $anchor = $('.s_tab a[href*=#]'),
$tabcontent = $('.st_c');
$anchor.each(function(){
$(this).click(function(){
var target = $(this).attr('href');
$anchor.removeClass('thmc2 thmtxt admtxt admbg').addClass('admtxt admbg');
$(this).toggleClass('thmc2 thmtxt admtxt admbg');
$tabcontent.hide();
$(target).show();
if( $('.tinycanvas').length > 0 ){
$('.tinycanvas').tinyscrollbar_update();
}
return false;
});
});
};
this.single_select = function(){
// single select
$('.ssl .ssl_item').each(function(){
var $des = $(this).find('.ssl_des');
$(this).on({
click: function(){
$(this).switchClass('','thmc1 active',0);
$(this).siblings('.thmc1').switchClass('thmc1 active','',0);
if( $des.length > 0 ){
$(this).parents('.ssl').find('.ssl_des').removeClass('thmtxt');
$des.addClass('thmtxt');
}
},
mouseenter: function(){
if( !$(this).hasClass('active') ){
$(this).addClass('thmc1');
if( $des.length > 0 ){
$des.addClass('thmtxt');
}
}
},
mouseleave: function(){
if( !$(this).hasClass('active') ){
$(this).removeClass('thmc1');
if( $des.length > 0 ){
$des.removeClass('thmtxt');
}
}
}
});
});
}
this.use_select2 = function(){
$('select:not(.select2-offscreen)').select2({
minimumResultsForSearch: -1
// minimumInputLength: -1
});
}
o.initialize();
}
orbitDesktop.prototype.themefolder = "themes";
orbitDesktop.prototype.widgetfolder = "desktop_widgets";
orbitDesktop.prototype.desktopId = "1";
orbitDesktop.prototype.notifyImgPath = "temp";
orbitDesktop.prototype.wallpaperPath = "/assets/stockBackground/";
orbitDesktop.prototype.iconPath = "/assets/icons/";
orbitDesktop.prototype.currentLanguage = "en";
orbitDesktop.prototype.currentUsername = "Harry";
var uselessfunction = function(){
$.post("/desktop/temp_func",{sectionid:"4f83e7bbbd98eb041600001d"});
}