
var panel_version = '3.2.0.5';

var api_url_base = 'apps2.mystart.com/api/';
//var api_url_base = 'localhost/namespace_apps.mystart.com/api/';

var api_version = '2_0';
var apps_api_version = '3_0';
var	disableTrigger = false;
var widgetsArray = new Array();
var mainContainer = null;

var hashTag = parseHashTag();
/*
var hashTag = {
    "id":"mystartapps",
    "v":"2.2",
    "fwv":""
};
*/
var alreadyInstalledString = 'The selected app is already installed.';

var api_url_apps = 'http://' + api_url_base + apps_api_version + '/apps/?agid=namespace_show&tb=' + hashTag['id'] + '&v=' + hashTag['v'] + '&fwv=' + hashTag['fwv'] + '&format=json';
var api_url_categories = 'http://' + api_url_base + api_version + '/categories/?agid=namespace_show&tb=' + hashTag['id'] + '&v=' + hashTag['v'] + '&fwv=' + hashTag['fwv'] + '&format=json';
var api_url_countries = 'http://' + api_url_base + api_version + '/countries/?active=true&order=order_index DESC';
var api_url_manifest = 'http://' + api_url_base + api_version + '/manifest/';
var api_url_rating = 'http://' + api_url_base + apps_api_version + '/rating/';
var api_url_publicurl = 'http://' + api_url_base + apps_api_version + '/publicUrl/'
var api_url_tile = 'http://' + api_url_base + api_version + '/tile/';


var oScrollbar = null;
var jqxhr = null;

var view_table_limit = 20;
var offset = 0;
var params = {offset: 0, more: false, sort: 'DateAdded'};
var moveToNextLoop = true;
var initialCall = true;

var tooltipText = ''; //'Double-click to add the app';

//temp variables used for handling dragging	
var mLeftBtnDown = 0; 	//by default the left button is not pressed
var mDragging = 0; 		//by default, not dragging
var mCrtPosMouse_X = 0; 
var mCrtPosMouse_Y = 0;
var pause = 1;

window.widgetData = {};
var namespace = {};
var dtxFramework = {
    IE : (navigator.userAgent.indexOf("MSIE") != -1 ), 
    MOZILLA : ((navigator.userAgent.indexOf("Firefox") != -1) || (navigator.userAgent.indexOf("Chrome") != -1)  || (navigator.userAgent.indexOf("Safari") != -1)),
    CHROME: (navigator.userAgent.indexOf("Chrome") != -1) || (navigator.userAgent.indexOf("Safari") != -1) 
};

function trackingEvent(action, category , label){
    if (window.external.trackEvent){
	    //alert("js: " + action + " | " + category + " | " + label);
        window.external.trackEvent(action, category, label);
    }
};

function externTrackingEvent(trackAction, trackCat, trackLabel){
	//alert("js: " + trackAction + " | " + trackCat + " | " + trackLabel);
    if (window.external.SendMessage)
        window.external.SendMessage('<message track="true" trackCategory="' + trackCat + '" trackAction="' + trackAction + '" trackLabel="' + trackLabel + '" />');
};

function setMainContainer(mc)
{
    mainContainer = mc;
}


function setVersion(){
    if (framework != null && framework.mainContainer){
        var tbName = framework.mainContainer.getAttribute("toolbarname");
        var version = framework.mainContainer.getAttribute("version") || "";
	 }else{
        var tbName = getParameterByName("name") || "";;
        var version = getParameterByName("v") || "";
	 }
     panel_version = version;
	 $('.panelVersion').html(panel_version);
	 $('#aboutTitle').html(tbName);
}


function proceesWidgets(widgetsArray){
    for (var i=0; i<widgetsArray.length;i++){
        id = widgetsArray[i];
        var elem = document.getElementById(id);
        if(elem)
            createInstalledImage(id);
    }
}



function setFFWidgets(sArray){
    try{
        if (sArray == null)
            return;
        wArray = new String(sArray).split(",");
    widgetsArray = wArray;
    proceesWidgets(wArray);
    }catch(e){
      //  alert(e.message + e.lineNumber);
    }
}


function getAppsAdded(){
    var wid = widgetsArray;
    setTimeout(function(){
		if(dtxFramework.MOZILLA){
           proceesWidgets(wid);
           return;
        }
        if (!widgetsArray)
            var widgetsArray = new Array();
        if (framework != null && mainContainer){
            for(var i=0;i<mainContainer.childNodes.length ;i++){
                var elem = mainContainer.childNodes[i];
                if(elem.tagName == "widget"){
                    if(elem.$guid != ""){
	                        widgetsArray.push(elem.$guid);
                    }
                }
            }
		    var widgetRegistry = framework.loadFile("widgets\\widgets.xml", true);
		    if (widgetRegistry != null) {
			    var widgetRegistryXML = self.framework.loadXML(widgetRegistry);
			    if (widgetRegistryXML != null) {
			        var widgets = widgetRegistryXML.documentElement.getElementsByTagName("widget");
				    for (var i = 0; i < widgets.length; i++) {
				        var widget   = widgets[i];
					    var guid     = widget.getAttribute("id");
	                    widgetsArray.push(guid);
				    }
			    }
		    }
        }
        proceesWidgets(widgetsArray);
    }, 300);
}


$(document).ready(function(){
	
	if(!!window.chrome){
		$('body').addClass('chrome');
	}

    setTimeout(function(){
         setVersion();
     }, 100);
	 oScrollbar = $("#scrollbar1");
	 oScrollbar.tinyscrollbar();
	
	$('#sortCol li').click(function(e){
		params.more = false;
		params.offset = 0;
		params.sort = $(this).data('sort');
		getApps(params);
		//ga('send', 'event', 'filter', 'sort', params.sort);
		trackingEvent("sort", "filter", params.sort);

		return false;
	});	
	
	$('#languageCol li').click(function(e){
		params.more = false;
		params.offset = 0;
		params.lang = $(this).data('language');
		getApps(params);
		//ga('send', 'event', 'filter', 'language', params.lang);
		trackingEvent("language", "filter", params.lang);
		return false;
	});	
	$('#addCustomSubmit').click(function(){
		$.fancybox.close();
	});
	$('#addCustomForm').submit(function(){
		var term = $('#addCustomInput').val().trim();
		if(term == ''){
			return false;
		}
		
		//ga('send', 'event', 'CustomShortcutPopup', 'submit', term);

		if(term.indexOf(' ') >= 0){ // there are spaces, so multiple words
			return false;
		}else if(term.indexOf('.') == -1) { // there are no dots	
			addCustomApp('www.'+term+'.com');
		}else if(term.indexOf('.') > 0){ //user entered URL
			addCustomApp(term);
		}
		return false;
	});
	
	$('#addForm').submit(function(){

		var term = $('#addInput').val().trim();
		if(term == ''){
			return false;
		}
		
		//ga('send', 'event', 'searchform', 'submit', term);
		trackingEvent("submit", "AppPanelSearch", term);

		//if after filtering only one app is found, install it
		if($('#widgetList').children('.widgetItem:not(#addCustomApp)').length == 1){
			 appToAdd = $('#widgetList').children('.widgetItem:not(#addCustomApp)').first();
			 initInstall(appToAdd.find('.appImageArea a').not().attr('href'));
		}else if(term.indexOf(' ') >= 0){ // there are spaces, so multiple words
			return false;
		}else if(term.indexOf('.') == -1) { // there are no dots	
			if($('#widgetList').children('.widgetItem:not(#addCustomApp)').length > 1){ // there are multiple results
				// we check if there are multiple apps that match the condition
				params.title = term;
				var url = prepareUrl();
				$.getJSON(url + '&callback=?', function(data) {
					if(data.total >= 1){
						initInstall(api_url_manifest + '?wid=' + data.widgets[0].id);
					}else{
						//no match
						addCustomApp('www.'+term+'.com');
					}
				});	
			}else{
				//there are no results
				addCustomApp('www.'+term+'.com');
			}
		}else if(term.indexOf('.') > 0){ //user entered URL
			// special case for ebay, where the publicurl is www.couponwinner.com
			if(term.indexOf('ebay') >= 0)
				term = 'couponwinner';

			params.publicurl = term;	
			params.title = null;
			var url = prepareUrl();
			$.getJSON(url + '&callback=?', function(data) {
				if(data.total >= 1){
					initInstall(api_url_manifest + '?wid=' + data.widgets[0].id);	
				}else{
					addCustomApp(term);
				}
			});
		}
		return false;

	});
	
	// create DropDownList from select HTML element                   
	$("select").uniform();
	
	$('#leftArrow').click(function(){
		var e = jQuery.Event("keydown");
		e.which = 37; // # Some key code value
		$("body").trigger(e);
	});

	$('#rightArrow').click(function(){
		var e = jQuery.Event("keydown");
		e.which = 39; // # Some key code value
		$("body").trigger(e);
	});

	$('#categoryPseudoList li').click(function(){
		if($(this).hasClass('mainCat')) // reset current 
			$(this).siblings().removeClass('current');

		if($(this).attr('id') != 'cat_custom')
			$(this).addClass('current');
		
		moveToNextLoop = true;
		 
	});
	
	$('.filterCol li').click(function(){
		$(this).siblings().removeClass('current');
		$(this).addClass('current');
		addFilterX(this);
	})
	
	$('.filterCol li').mouseover(function(){
		$(this).children('.closeFilter').css('visibility', 'visible');
	}).mouseout(function() {
		$(this).children('.closeFilter:not(.current)').css('visibility', 'hidden');
    });
	
	$('#cat_featured').click(function(e){
		resetFilters();
		params.title = '';
		params.publicurl = '';
		params.cat = '';
		params.sort = 'DateAdded';
		params.more = false;
		params.offset = 0;
		getApps(params);
		//ga('send', 'event', 'filter', 'featured');
		if(e.isTrigger == undefined)
			trackingEvent("click", "AppPanelCategories", "featured");
	});
	
	$('#cat_most_popular').click(function(e){
		resetFilters();
		params.title = '';
		params.publicurl = '';
		params.cat = '';
		params.sort = 'DownloadCountPeriod';
		params.more = false;
		params.offset = 0;
		getApps(params);
		moveToNextLoop = true;
		//ga('send', 'event', 'filter', 'most_popular');
		if(e.isTrigger == undefined)
			trackingEvent("click", "AppPanelCategories" , "most_popular");
	});
	
	$('#cat_latest').click(function(e){
		resetFilters();
		params.title = '';
		params.publicurl = '';
		params.cat = '';
		params.sort = 'DateAdded';
		params.more = false;
		params.offset = 0;
		getApps(params);
		//ga('send', 'event', 'filter', 'latest_apps');
		if(e.isTrigger == undefined)
			trackingEvent("click", "AppPanelCategories" , "latest_apps");

	});
	
	$('#cat_custom').click(function(){
		$('#addCustomInput').val('').focus();
		//ga('send', 'event', 'Filter', 'custom_shortcut');
	});
	
	getCategories();
	getCountries();
    getAppsAdded();
	
	//simulate click on "Featured" to get featured apps
	$('#cat_featured').trigger('click');
	
	initHoverImage();	
	initArrowKeyPress();

	$('.toggleFilter').click(function(){
		if($(this).data('toggle') == 'filterBox'){
			if($('#filterBoxCategories').is(':visible')){
				$('#filterBoxCategories').hide();
			}
			$('#filterBox').fadeToggle(function(){
				if($('#filterBox').is(':visible')){
				//	ga('send', 'event', 'Filter', 'show');
				}
			});
		}
		else if($(this).data('toggle') == 'filterBoxCategories'){
			if($('#filterBox').is(':visible')){
				$('#filterBox').hide();
			}
			
			$('#filterBoxCategories').fadeToggle(function(){
				if($('#filterBoxCategories').is(':visible')){
					//ga('send', 'event', 'FilterCategories', 'show');
				}
			});
		}
	})

	$('#closeFilterBox').click(function(){
		//ga('send', 'event', 'Filter', 'closeX');
		// if no filter is set, remove current class
		if($('#filterBox .current').length == 0)
			$('#filters').removeClass('current');
	});

	$('#closeFilterBoxCategories').click(function(){
		//ga('send', 'event', 'FilterCategories', 'closeX');
		// if no filter is set, remove current class
		if($('#categoryList .current').length == 0)
			$('#filter_categories').removeClass('current');
	});

	 $('#cboxClose').click(function(){
		 if (panelWindow) {
			 panelWindow.close();
		 }	
		// //ga('send', 'event', 'panel', 'closeX');
		// //trackingEvent("panel", "closeX", "");
	 });
   
	
	$('#addInput').keyup(function(event){
		if((event.keyCode > 45 && event.keyCode < 90) || event.keyCode == 8)
		{
			term = $(this).val().trim();
			if(term.length > 0){
				// when starting typing, remove featured
				$('#categoryPseudoList').children().removeClass('current');
				params.more = false;
				params.offset = 0;
				params.search = '%'+term+'%';
				params.callback = addCustomAppIcon;
				getApps(params);
			}else{
				$('#cat_featured').trigger('click');
				$('#addCustomApp').remove();
			}
		}
	});
	
	$('.fancybox').fancybox({live: false});

	$('.closePopup').click(function(){
		$.fancybox.close();
	})
		
	$('#ico_version').click(function(){
		//ga('send', 'event', 'AppPanelAbout', 'click');
		trackingEvent("click", "AppPanelAbout", "");
	});
	
	$('#ico_feedback').click(function(){
		//ga('send', 'event', 'AppPanelFeedback', 'click');		
		trackingEvent("click", "AppPanelFeedback", "");
	});

	initSubmit();
	
	setupDraggableComponent();	
});

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

function setupDraggableComponent() {
	try	{
		var mDraggedMousedown = function(evt) {
			try {

				if(evt.which == '1') {
					evt.target.setCapture();
					mLeftBtnDown = 1; //left button pressed!
					mDragging = 0;
				}
				else
					mLeftBtnDown = 0; 			
			} catch(e) {
				framework.getLogger().info(e.message);
			}		
		};
		
		var mDraggedMouseup = function(evt) {
			try {
				evt.target.releaseCapture();
				mLeftBtnDown = 0; //button released
				mDragging = 0;
			} catch(e) {
				framework.getLogger().info(e.message);
			}		

		};
		
		var mDraggedMousemove = function(evt) {
			try {
				if (evt.which != '1') {
					mLeftBtnDown = 0;
					mDragging = 0;
				}
				if (mLeftBtnDown == 1) {
					mCrtPosMouse_X = evt.screenX;
					mCrtPosMouse_Y = evt.screenY;
				}
				if (mLeftBtnDown == 1 && mDragging == 0) {
					mDragging = 1;
					//launch the handler
					var draggedWin = panelWindow;
					var timerUp = 0;
					doDragHandle(draggedWin, mCrtPosMouse_X, mCrtPosMouse_Y, timerUp); 	
				}
			} catch(e) {
				framework.getLogger().info(e.message);
			}
		};
		
		$( "#idDraggable" ).mousedown( mDraggedMousedown );
		$( "#idDraggable" ).mouseup( mDraggedMouseup );
		$( "#idDraggable" ).mousemove( mDraggedMousemove);

	} catch(e) {
		framework.getLogger().info("setupDraggableComp error: " + e.message);
	}	
};

function doDragHandle(draggedWin, mPrevPosX, mPrevPosY, timerUp) {
	try {
		if (mLeftBtnDown == 1) {
			var mPosMouseNow_X = mCrtPosMouse_X;
			var mPosMouseNow_Y = mCrtPosMouse_Y;
			var mCrtPosPanel_X = 0;
			var mCrtPosPanel_Y = 0;

			if (dtxFramework.MOZILLA) {
				mCrtPosPanel_X = window.screenX;
				mCrtPosPanel_Y = window.screenY;
				var deltaX = mPosMouseNow_X - mPrevPosX;
				var deltaY = mPosMouseNow_Y - mPrevPosY;
				window.moveFFPanelTo(mCrtPosPanel_X + deltaX, mCrtPosPanel_Y + deltaY);
			} else { //IE
				try{
					draggedWin.drag();
					return;
				}catch(e){
					framework.getLogger().info(e.message);
				}
				
				mCrtPosPanel_X = window.screenLeft;
				mCrtPosPanel_Y = window.screenTop;
				var deltaX = mPosMouseNow_X - mPrevPosX;
				var deltaY = mPosMouseNow_Y - mPrevPosY;
				draggedWin.show(mCrtPosPanel_X + deltaX, mCrtPosPanel_Y + deltaY);
			}

			if (dtxFramework.MOZILLA) {
				var delay = function() { doDragHandle(draggedWin, mPosMouseNow_X, mPosMouseNow_Y, timerUp); };
				timerUp = setTimeout(delay, pause);
			}
		} else {
			clearTimeout(timerUp);
			mDragging = 0;
		}
	} catch(e) {
		framework.getLogger().info(e.message);
	}
};
function initSubmit(){
	$('.mailSubmit').submit(function() {
		//var url = 'http://appgrid-apps.mystart.com/api/sendmail.php';
		var url = 'http://' + api_url_base  + 'sendmail.php';
		var postData = $(this).serialize();

		if($(this).children('input[name=email]').val() != ''){
			if(validateEmail($(this).children('input[name=email]').val()) == false){
				alert('The email adress provided is not valid.');
				return false;
			}	
		}
		
		if($(this).find('.details').html() != null)
			postData += '&details=' + encodeURIComponent($(this).find('.details').html());

		postData += "&callback=?";

	    $.getJSON( url, postData , function(data) {
	    	if(data.output)
	    		var message = 'Your message has been sent. Thank you!';
	    	else
	    		var message = 'There was an error. Please try again later.';
	    	
	    	$.fancybox({content: message, padding: [15,35,15,15]});
	    });
	    
	    var id = $(this).parent().attr('id');
	    if(id == 'popupFeedback'){
	    	//ga('send', 'event', 'AppPanelFeedback', 'submit');	
			trackingEvent("submit", "AppPanelFeedback", "");
	    }else if(id == 'popupReport'){
	    	//ga('send', 'event', 'AppPanelReport', 'submit');
			trackingEvent("submit", "AppPanelReport", "");
	 	}
		return false;
	});
}

function addCustomApp(appUrl){

	// add http:// if not included
	if (!/^http(s)?:\/\//.test(appUrl)) {
		appUrl = "http://" + appUrl;
    }
	
	if (framework && framework.mainContainer){
        var manifestUrl =  "http://" + api_url_base + apps_api_version + "/custom_manifest/?publicurl=" + appUrl;
	   	 framework.mainContainer.$installWidget(manifestUrl, null);
	}
};

function addFilterX(obj){
	$(obj).parent().find('.closeFilter').removeClass('current').css('visibility', 'hidden');
	$(obj).children('.closeFilter').addClass('current').css('visibility', 'visible');

	$('.closeFilter').click(function(){
		$(this).parent().removeClass('current');

		//remove the filter from params
		if($(this).parent().parent().parent().attr('id') == 'countryCol')
			params.country = '';
		else if($(this).parent().parent().parent().attr('id') == 'languageCol')
			params.lang = '';
		else if($(this).parent().parent().parent().attr('id') == 'sortCol')
			params.sort = '';

		$(this).removeClass('current').css('visibility', 'hidden');
		params.more = false;
		params.offset = 0;
		getApps(params);
		return false;
	});
	
}	

function showMoreApps(){
	if($('#widgetList.overview').height() + $('#widgetList.overview').position().top - $('.viewport').height() < 75){
		loadMoreApps();
		getAppsAdded();
    }	
}

function loadMoreApps(){
	 params.offset = params.offset + view_table_limit;
	 params.more = true;
	 getApps(params);
}

function resetFilters(){
	$('#addInput').val('');
	$('#details').show();
	$('#filterBox #countryCol li.current').removeClass('current');
	$('#filterBox #sortCol li.current').removeClass('current');
	$('#filterBox #languageCol li.current').removeClass('current');
	$('#categoryList li.current').removeClass('current');
	$('#categoryList li .closeFilter.current ').removeClass('current').css('visibility', 'hidden');
	params.country = '';
	params.lang = '';
	params.cat = '';
	$('#filterBox .closeFilter.current').css('visibility', 'hidden').removeClass('current');
	params.search = '';
	getAppsAdded();
}

function getCountries(){
	$.getJSON(api_url_countries + '&callback=?', function(data) {
		  var items = [];
		
		  $.each(data, function(key, val) {
			if(val.name.length > 17)
				val.name = val.name.substr(0 ,17) + '...';
		    items.push('<li data-country="' + val.id + '">' + val.name + '<div class="closeFilter"></div></li>');
		  });
	
		$('#countryCol ul').html(items.join(''));
		
		// if you click on a country		 
		$('#countryCol li').click(function(){
		//	ga('send', 'event', 'Filter', 'country', $(this).data('country'));
			trackingEvent("country", "filter", $(this).data('country'));
			$(this).siblings().removeClass('current');
			$(this).addClass('current');		
			params.more = false;
			params.offset = 0;
			params.country = $(this).data('country');
			getApps(params);
			addFilterX(this);
			return false;
		});	
		
		$('#countryCol li').mouseover(function(){
			$(this).children('.closeFilter').css('visibility', 'visible');
		}).mouseout(function() {
			$(this).children('.closeFilter:not(.current)').css('visibility', 'hidden');
	    });
		 		 
	});	
}

function getCategories(){
	var toolbar = $.url.param('toolbar');
		  $.getJSON(api_url_categories + '&callback=?', function(data) {
		  var items = [];

		  $.each(data, function(key, val) {
			// hide the first item "all"  
			if(key == 0)
				items.push('<li data-id="0" id="cat_0" class="hide">' + val.name + '<div class="closeFilter"></div></li>');
			else
				items.push('<li data-id="'+ val.id +'" id="cat_' + val.id + '">' + val.name + '<div class="closeFilter"></div></li>');	
		  });

		 $('#categoryList').empty().html(items.join(''));
	 
		$('#categoryList li').mouseover(function(e){
			$(this).children('.closeFilter').css('visibility', 'visible');
		}).mouseout(function() {
			$(this).children('.closeFilter:not(.current)').css('visibility', 'hidden');
	    });
		 		 
		 // if you click on a category
		 $('#categoryList li').click(function(e){
			 $('#addInput').val('');
			 $('#categoryList').find('li').removeClass('current');
			 $('#categoryList').find('.closeFilter').removeClass('current').css('visibility', 'hidden');
			 $(this).addClass('current');
			 $(this).children('.closeFilter').addClass('current').css('visibility', 'visible');
			 
			 $('#details').show();
			 var id = $(this).attr('id');	
			 params.more = false;
			 params.offset = 0;
			 params.cat = $(this).data('id');
			 getApps(params);
			 //ga('send', 'event', 'filter', 'category', $(this).html());
			 if(e.isTrigger == undefined)			 
			    trackingEvent("filter", "category",$(this).html());
		 });	 
		 
		 // if you click on a category
		 $('#categoryList li .closeFilter').click(function(){
			 $('#categoryList').find('li').removeClass('current');
			 $('#categoryList').find('.closeFilter').removeClass('current').css('visibility', 'hidden');
			 params.cat = '';
			 getApps(params);
			 return false;
		 });
	});

}

function addEventsToButtons(parent){
	$('#' + parent + ' .widgetItem').click(function(e){
        moveToNextLoop = false;
        $(this).siblings().removeClass('current');
        $(this).addClass('current');
        //$(this).context.setAttribute("added", "true");
        updateAppDetails();
		
		if(e.isTrigger == undefined)
		{
			var appId = getCurrentWidgetId();
			if(e.isTrigger == undefined)
				externTrackingEvent('click', 'AppPanelApp', window.widgetData[appId].externalID);
		}
		
	    
	    if (parent == "widgetList"){
	        parentContainer = "details";
	    	$('#details').show();

	    }else{
	        parentContainer = "extendedDetails";
	    }
        var addedImageClone = $('#' + parentContainer + ' .addedImage').clone();
	
	    $('#' + parentContainer + ' .addedImage').remove();
	    
	    addedImageClone.appendTo('#' + parentContainer + ' .appImageArea');
	    
        return false;
	});
	
	
     // if you doubleclick on an item, install it
    $('#' + parent + ' .widgetItem').dblclick(function(e){
		//initInstall($(this).find('.appImageArea a').attr('href'));
		//$('#dtx-widgetbutton-summary-add-image .button').trigger('click');
		//$('#dtx-widgetbutton-summary-add-image').trigger('click');
		guid = this.firstChild.getAttribute("id");
		widgetsArray.push(guid);
	    getAppsAdded();
	    $(this).trigger('click');
	});
}

function prepareUrl(){
	var url = api_url_apps + '&limit=' + view_table_limit;
	if(params)
	{
		if(params.cat) {
			url += '&cid=' + params.cat;
		}
		if(params.offset) {
			url += '&start=' + params.offset;
		}
		else {			
			url += '&start=0';
		}
		if(params.sort && params.sort != 0)	{
			url += '&sort=' + params.sort;
		}
		if(params.lang && params.lang != 0)	{			
			url += '&lang=' + params.lang;
		}
		if(params.country && params.country != 0) {			
			url += '&country=' + params.country;
		}
		if(params.search){
			url += '&search=' + encodeURIComponent(params.search);
		}
		if(params.title){
			url += '&title=' + encodeURIComponent(params.title);
		}
		if(params.publicurl){
			url += '&publicurl=' + encodeURIComponent(params.publicurl);
		}
	}
	
	return url;
}

function getApps(params){
try{
	$('#extendedDetails').hide();
	$('#list').show();
	
	var url = prepareUrl();
	
	// when doing a search, ignore the featured param
	if($('#cat_featured').hasClass('current')) {
		url += '&featured=true';
	}
		
	// if not more, first delete all current items
	if(params && params.more !== true) {	
		$('#widgetList').html('<div id="loader"><img src="images/ajax-loader.gif" /></div>');
	}
	else {
		$('#showMoreApps').remove();
		$('#widgetList').append('<div id="loader"><img src="images/ajax-loader.gif" /></div>');	
	}	

	// if there is a current request, abort it
	if(jqxhr != null && typeof jqxhr == 'object' && typeof jqxhr.abort == 'function'){
		jqxhr.abort();
	}
	
	jqxhr = $.getJSON(url + '&callback=?', function(data) {
		try{
		if(data.total > 0){	
			 $('#details').show();
			
			 var items = [];
			 $.each(data.widgets, function(key, val) {
				
				val.widgetManifestURL = api_url_manifest + '?wid=' + val.id;	
				
				var rating = new Number(val.rating);
				if(rating == 0)
					rating = 3;
				
				// put all apps into array with key equals AppId
				window.widgetData[val.id] = val;
								
			    items.push('<div class="widgetItem" id="app_' + val.id + '">' 
	    			+ '<div manifest="' + val.id + '" id="' + val.externalID + '" class="appImageArea">'
	    			+ '<a id="title_' + val.id + '" xtitle="'+tooltipText+'" onclick="return false;" href="' + val.widgetManifestURL + '">'
	    			+ '<img xondblclick="addWidget(document)" class="appImage" src="http://' + val.thumbLocation +'">'
	    			+ '</a>'
	    			+ '</div>'
					+ '<div><div onmouseout="backToOriginalStars(event, this);" data-rating="'+rating+'" data-id="'+val.id+'" class="starRating" title="Rating: ' + rating.toPrecision(2) + '"></div></div>'
					+ '<div style="clear:both;"></div>'
					+ '<div class="appTitle" title="' + val.description + '">' + val.title + '</div>'
					+ '<div class="appDescription"><span>' + val.description + '</span></div>' 		    			
	    			+ '</div>');
			 });
			 
			 $('#loader').replaceWith(items.join(''));
			 
			 addStarRating();
             getAppsAdded();
			 
			 // display "show more" link if there is more
			 if(data.total > data.start + view_table_limit)
				 $(document).bind('scroll', showMoreApps);
			 else
				 $(document).unbind('scroll', showMoreApps);
			 
			addEventsToButtons('widgetList');

			 // if none is currently selected, select first one
			 if(params.more === false)
			 {			 
				 $('#widgetList .widgetItem:first').trigger('click');
			 }

			 makeQtips($('#content .appImage'));	 

			 setTimeout(function(){
				 if(params.offset == 0){
					 oScrollbar.tinyscrollbar_update();
				 } else {
					 oScrollbar.tinyscrollbar_update('relative');
			 }}, 300);
			 if (disableTrigger)
			    $('#addInput').focus();
		}
		else
		{
			$('#content #round_corners_table').hide();
			$('#details').hide();
			$('#content #widgetList').html('<div id="noCategoryFound">No apps found.</div>');

			oScrollbar.tinyscrollbar_update();
		}	

		// call callback 
		if(typeof params.callback == 'function'){
			params.callback();
			params.callback = null;
		}
	}catch(e) {
		// if there is a current request, abort it
		if(jqxhr != null && typeof jqxhr == 'object' && typeof jqxhr.abort == 'function'){
			jqxhr.abort();
		}
	}
	}).error(function(jqXHR, textStatus, errorThrown) {
		jqxhr.abort();
    }).fail(function(jqXHR, textStatus, errorThrown) { 
		jqxhr.abort();
	});
	}catch(e) {
		// if there is a current request, abort it
		if(jqxhr != null && typeof jqxhr == 'object' && typeof jqxhr.abort == 'function'){
			jqxhr.abort();
		}
	}
}

function initInstall(manifestUrl){
	// if (framework && framework.mainContainer){
		// framework.mainContainer.$installWidget(manifestUrl, null);
	// }
	return ;
}

function getManifestWorkaround(url){
	if ($.browser.msie && window.XDomainRequest) {
		// Use Microsoft XDR
		var xdr = new XDomainRequest();
		xdr.open("get", url);
		xdr.onload = function() {
			try{
				// XDomainRequest doesn't provide responseXml, so if you need it:
				var xmlObj = new ActiveXObject("Microsoft.XMLDOM");
				xmlObj.async = false;
				xmlObj.loadXML(xdr.responseText);
									
				var externalId = xmlObj.getElementsByTagName("app")[0].getAttribute("id");

				// before adding, we check if the external ID already exists
				for(var x = 0; x < namespace.Apps.length; x++){
					if(namespace.Apps[x].guid == externalId){
						//alert(alreadyInstalledString);
						return false;
					}		
				}

				var tileIcon = xmlObj.getElementsByTagName("action")[0].getAttribute("tile");
				var appUrl = xmlObj.getElementsByTagName("panel")[0].getAttribute("url");
				addApp(externalId, tileIcon, appUrl);
									
			}catch(e){ };
		};
		xdr.send();
	}
}

function addApp(externalId, tileIcon, appUrl){
    for(i=0;i<namespace.Apps.length;i++){
        var id= namespace.Apps[i].getAttribute("id");
        if (id == externalId){
            alert(alreadyInstalledString);
            return;
        }
        else
        {
            continue
        }
     }
    
    var manifestUrl =  "http://" + api_url_base + api_version + "/custom_manifest/?publicurl=" + appUrl;
	window.external.SendMessage('<message type="requestAppInstall" id="' + externalId + '" url="' + manifestUrl + '" />');
    $('#ico_confirmation').click();
	$('#confirm_ok').click(function(){
		$.fancybox.close();
	});
    getAppsAdded();
    return;
}

function makeQtips(selector){
	   $(selector).each(function() {
	      if( typeof $(this).data('qtip') === 'object') { return true; }
	 
	      $(this).qtip({
				content: 'Double-click to add the app',
				position: {
					container: $('#wrapper'),
					my: "bottom center",
					at: "top center"
				},
				show: {
					event: "mouseover"
				},
				hide: {
					event: "mouseout"
				},
				style: {
					width: 90,
					tip: true,
					classes: "qtip-light"
				}
			});
	   });
}

function initArrowKeyPress(){
	$(document).keydown(function(e){
		try{
			// do this only if the input field is not in focus
			if($('#addInput').is(':focus'))
				return;
			
			var currentItem = $('#widgetList .current');
			
			var hasChanged = false;
			var keyCode = e.keyCode || e.which,
		    	arrow = { pageup: 33, pagedown: 34, end: 35, home: 36, left: 37, up: 38, right: 39, down: 40 };

			var positionCurrent = $('#widgetList .current').position();
			var itemsPerRow = 5;
			var currentRow = Math.floor(currentItem.prevAll().size()/itemsPerRow) + 1;  
			
			  switch (keyCode) {
			    case arrow.home:
			    	if(currentItem.is(':first-child') !== true){
			    		// go to first element
			    		currentItem.removeClass('current');
			    		currentItem.parent().children(':first').addClass('current');
			    		oScrollbar.tinyscrollbar_update();
			    	}
			    break;
			    case arrow.end:
			    	if(currentItem.is(':last-child') !== true){
			    		// go to last element
			    		currentItem.removeClass('current');
			    		currentItem.parent().children(':last').addClass('current');
			    		oScrollbar.tinyscrollbar_update('bottom');
			    	}	
			    break;
			    case arrow.left:
			    	if(currentItem.prev('.widgetItem').length > 0){	
			    		currentItem.removeClass('current');
			    		currentItem.prev('.widgetItem').addClass('current');
			    	}
			    	else
			    	{
			    		oScrollbar.tinyscrollbar_update();
			    	}	
			    break;
			    case arrow.up:
			    case arrow.pageup:
			    	if(currentItem.prevAll().length > 4){
			    		currentItem.removeClass('current');
			    		currentItem.prevAll().eq(4).addClass('current');
		  			}
			    	else
			    	{
			    		oScrollbar.tinyscrollbar_update();
			    	}	
			    break;
			    case arrow.right:
			    	if(currentItem.next('.widgetItem').length > 0){
			    		currentItem.removeClass('current');
			    		currentItem.next('.widgetItem').addClass('current');
		  			}
			    	else
			    	{
			    		oScrollbar.tinyscrollbar_update('bottom');
			    	}	
			    break;
			    case arrow.down:
			    case arrow.pagedown:
			    	if(currentItem.nextAll().eq(4).length > 0){
			       		currentItem.removeClass('current');
			    		currentItem.nextAll().eq(4).addClass('current');
		  			}
			    	else
			    	{
			    		oScrollbar.tinyscrollbar_update('bottom');
			    	}	

			    break;	
			  }

			var numRows = Math.floor($('#widgetList').children().size()/itemsPerRow);
			var newItem = $('#widgetList .current');
			var newRow = Math.floor(newItem.prevAll().size()/5) + 1;  

			if(currentRow != newRow){ // if row has changed
				// go down until 2nd to last row	  
				if(currentRow < newRow && newRow > 3 && currentRow < numRows)  
				{
			    	oScrollbar.tinyscrollbar_update(positionCurrent.top);
				}
				
				if(currentRow < newRow && currentRow + 1 == numRows)
					loadMoreApps();

				if(currentRow > newRow && currentRow <= numRows && currentRow > 1)  // going up
				{
					var offset = 0;
					if(newRow > 1)
						offset = positionCurrent.top - 92;

			    	oScrollbar.tinyscrollbar_update(offset);
				}
			}  

			// update the details whenever app is changed
			if(currentItem.attr('id') != newItem.attr('id'))
				updateAppDetails();			
			
		}catch(ex){
			alert(ex.message);
		}
		
	});
}

function updateAppDetails()
{
	try{
		$('#innerDetailsArea').css('opacity',0);
		$('#innerDetailsArea').empty();
		$('#content #round_corners_table').show();
		var widgetClone = 	$('#widgetList .current').clone();
		$(widgetClone).attr('id', $(widgetClone).attr('id').replace("app_", "apx_"));
	    widgetClone.appendTo('#innerDetailsArea');
	    var manifest = $(widgetClone).attr('id').substr(4,5);
		$('#div_' + manifest).remove();
	
		//$('#widgetList .current').clone().appendTo('#innerDetailsArea');
		//$('#innerDetailsArea .widgetItem').removeClass('current');
		//	
		//// replace image location
		//var thumbIcon = $('#innerDetailsArea .appImage').attr('src');
		//$('#innerDetailsArea .appImage').attr('src', thumbIcon.replace('thumb_icon.png', 'tile_icon.png'));
		//
		// set new title
		var title = 'Click to show full details';
		$('#innerDetailsArea .toggleDetails').attr('title',title);
		
		//rewrite id
		$('#innerDetailsArea .appImageArea').attr('id',$('#innerDetailsArea .appImageArea').attr('id') + '_details');

		var p=$('#innerDetailsArea .appDescription span');
		var divh=$('#innerDetailsArea .appDescription').height();

		//var descLength = 120;
		var descLength = 115;
		if($(p).html().length > descLength) {
			var description = $(p).html().substring(0, descLength);
			description = description.replace(/\W*\s(\S)*$/, '...');
			$(p).html(description);
		}	
			
		$('#innerDetailsArea .appDescription').append('<a href="#" class="toggleDetails">[More details]</a>');

		var appId = getCurrentWidgetId();

		/*$('#innerDetailsArea').append('<div id="buttonArea" class="formButtons"><div id="dtx-widgetbutton-summary-add-image" class="dtx-add-button"><a onclick="return false;" data-id="'+ window.widgetData[appId].externalID +'" href="' + window.widgetData[appId].widgetManifestURL + '" class="button primary">Add</a></div>'
					+ '<div class="dtx-launch-button" ><a onclick="return false;" href="' + window.widgetData[appId].widgetManifestURL + '" class="button"><img id="dtx-widgetbutton-summary-run-image" class="hoverImage" src="images/btn-launch.png"></a></div></div>');
		*/
		$('#innerDetailsArea').append('<div id="buttonArea" ><div class="dtx-add-button" ><a onclick="return false;" href="' + window.widgetData[appId].widgetManifestURL + '" > <img id="dtx-widgetbutton-summary-add-image" class="hoverImage" src="images/btn-add.png"></a></div><div class="dtx-launch-buuton" ><a onclick="return false;" href="' + window.widgetData[appId].widgetManifestURL + '" ><img id="dtx-widgetbutton-summary-run-image" class="hoverImage" src="images/btn-launch.png"></a></div></div>');
		
		$('#innerDetailsArea').find('div.starRating').attr('id' , 'rating_'+appId);

		if (document.createEventObject){
		    // dispatch for IE
		    var event = document.createEventObject();
			event.type = 'readystatechange';
			document.fireEvent('onreadystatechange',event);
		}else{
		    // dispatch for firefox + others
		    var evt = document.createEvent("HTMLEvents");
		    evt.initEvent('readystatechange', true, false ); // event type,bubbling,cancelable
		    z = document.dispatchEvent(evt);
		}
					
		$('.toggleDetails').click(function(e){
		    if (e.target.id == "extendedDetailsBack")
		        return;
			if (!$('#extendedDetails').is(':visible')) {
			    moveToNextLoop = false;
			    showExtendedDetails();	
			    addEventsToButtons('extendedDetails');
			    $('#extendedDetails  .widgetItem').trigger('click');
			    var currentId = getCurrentWidgetId();
			    var currentItem = window.widgetData[currentId];
			    if(e.isTrigger == undefined)
				    trackingEvent('click', 'AppPanelAppDetails', currentItem.externalID);
		    }
		    return;
		});
		
		// if extended details currently shows, also update it
		//if ($('#extendedDetails').is(':visible')) {
		//	showExtendedDetails();
		//}
		
		$('#innerDetailsArea').animate({ opacity: 1 }, 300);
		
		initHoverImage();

		$('#innerDetailsArea .appImageArea a').attr('title',tooltipText);
		
		$('.dtx-add-button a').click(function(){
			initInstall($(this).attr('href'));
		});
		
	//	$('.dtx-launch-button a').click(function(){
		//	 externalId = $(this).data('id');
			 //ga('send', 'event', 'app', 'launch', externalId);
			 //trackingEvent("app", "launch", externalId);
	//	});
		
		makeQtips($('#innerDetailsArea .appImageArea'));	 

		// if you doubleclick on an item, install it
		$('#innerDetailsArea .widgetItem').unbind('dblclick').dblclick(function(){
			if (!$(this).context.getAttribute("added")){
				$(this).trigger('click');
				initInstall($(this).find('.appImageArea a').attr('href'));
				$(this).context.setAttribute("added", "true");
				$('#dtx-widgetbutton-summary-add-image .button').trigger('click');
				getAppsAdded();	
			}else{
				// alert(alreadyInstalledString);
				return false;
			}	
		});	
		
	} catch(e){/*alert('updateAppDetails: ' + e.message);*/}
}

function showExtendedDetails(){
	$('#extendedDetails').html($('#widgetList .current').clone());
	
	// replace image location
	// var thumbIcon = $('#extendedDetails .appImage').attr('src');
	// $('#extendedDetails .appImage').attr('src', thumbIcon.replace('thumb_icon.png', 'tile_icon.png'));
	
	$('#details').hide();
	var currentId = getCurrentWidgetId();
	var currentItem = window.widgetData[currentId];
	
	var rating = new Number(currentItem.rating);
	
	$('#extendedDetails').find('div.starRating').attr('id' , 'ratingDetails_'+currentId);
	var appId = getCurrentWidgetId();
	$('#extendedDetails .widgetItem').append('<div id="buttonArea" class="formButtons"><div class="dtx-add-button" ><a onclick="return false;" href="' + window.widgetData[appId].widgetManifestURL + '" > <img id="dtx-widgetbutton-details-add-image" xclass="hoverImage" src="images/btn-add.png"></a></div></div></div>');
	
	$('#extendedDetails').append('<p class="line"></p>');
	
	$('#extendedDetails').append('<div id="extendedDetailsItems"></div>');
	$('#extendedDetailsItems').append('<div class="extendedDetailsItem">Date Added: <span class="detailValue">' + currentItem.dateAdded + '</span></div>');
	$('#extendedDetailsItems').append('<div class="extendedDetailsItem">Rating: <span class="detailValue">' + rating.toPrecision(2) + ' ('+currentItem.totalRatings+')</span></div>');
	$('#extendedDetailsItems').append('<div class="extendedDetailsItem">Total installations: <span class="detailValue">' + currentItem.downloadCount + '</span></div>');
	$('#extendedDetailsItems').append('<div class="extendedDetailsItem">Published by <span class="detailValue">' + currentItem.publisherName + '</span></div>');
	$('#extendedDetailsItems').append('<div class="extendedDetailsItem">Last 30 days installations: <span class="detailValue">' + currentItem.downloadCountPeriod + '</span></div>');
	$('#extendedDetailsItems').append('<div class="extendedDetailsItem">Developed by <span class="detailValue">' + currentItem.developerName + '</span></div>');
	
	$('#extendedDetails').append('<p class="line"></p>');
	$('#extendedDetails').append('<a class="toggleDetails" href="#" id="extendedDetailsBack">Back</a>');
	$('#extendedDetails').append('<ul class="iconLinks"><li id="ico_report"><a href="#popupReport" id="reportLink" class="fancybox">Report this app</a></li></ul>');
	
	$('#appname').html(currentItem.title);
	$('#addid').html(currentItem.externalID);
	$('#productname').html(currentItem.title);

	$('#list').hide();	
	$('#extendedDetails').show();

	$('#extendedDetailsBack').click(function(e){
		$('#details').show();
		$('#extendedDetails').hide();
		$('#list').show();
		if(e.isTrigger == undefined)
			trackingEvent('click', 'AppPanelBack', currentItem.externalID);
		return false;
	});	
	
	$('#ico_report').click(function(){
		//ga('send', 'event', 'AppPanelReport', 'click', currentItem.externalID);
		trackingEvent("open", "AppPanelReportApp", currentItem.externalID);
		
	})

	$('#extendedDetails .appImageArea a').attr('title',tooltipText);
	
	makeQtips($('#extendedDetails .appImageArea'));	 
	$('#reportLink').fancybox({live: false, padding: [0]});
	$('#dtx-widgetbutton-details-add-image a').click(function(){
		initInstall($(this).find('.appImageArea a').attr('href'));
		getAppsAdded();
		$('#extendedDetails .widgetItem').trigger('dblclick');
	});
	// if you doubleclick on an item, install it
	$('#extendedDetails .widgetItem').unbind('dblclick').dblclick(function(){
		initInstall($(this).find('.appImageArea a').attr('href'));
		$('#dtx-widgetbutton-summary-add-image .button').trigger('click');
		getAppsAdded();	
	});	
}

function getCurrentWidgetId(){
	var id = $('#innerDetailsArea .widgetItem').attr('id');
	return id.substr(4,id.length);
}

// this function will add a hover effect to all images that have a hoverImage-class
function initHoverImage() {
	$('.hoverImage').unbind('hover');
	var origImg;
	var hoverImg;
	$('.hoverImage').hover(function(){
		hoverImg = origImg = $(this).attr('src');
		var pos = origImg.lastIndexOf('.');
        if(pos > 0){
          hoverImg = hoverImg.substr(0,pos) + '-over' + hoverImg.substr(pos);
        }  
		$(this).attr('src', hoverImg);
	}, function(){
		$(this).attr('src', origImg);
	});
}

function moveToNextApp() {
	// move only if moveToNextApp is true
	if(moveToNextLoop && $('#widgetList .widgetItem').length > 0) 
	{	
		var currentItem = $('#widgetList .current');
		currentItem.removeClass('current');
		if(currentItem.next('.widgetItem').length > 0)
			currentItem.next('.widgetItem').addClass('current');
		else
			currentItem.siblings('.widgetItem').filter(":first").addClass('current');
			
		updateAppDetails();
	}
}

function addStarRating() {
	var starHtml = 	  ' <span onclick="rateApp(this);" class="star" data-stars="1"><img onmouseover="initChangeRatingStars(this);" src="images/star_blank.png" alt="" /></span>'
					+ ' <span onclick="rateApp(this);" class="star" data-stars="2"><img onmouseover="initChangeRatingStars(this);" src="images/star_blank.png" alt="" /></span>'
					+ ' <span onclick="rateApp(this);" class="star" data-stars="3"><img onmouseover="initChangeRatingStars(this);" src="images/star_blank.png" alt="" /></span>'
					+ ' <span onclick="rateApp(this);" class="star" data-stars="4"><img onmouseover="initChangeRatingStars(this);" src="images/star_blank.png" alt="" /></span>'
					+ ' <span onclick="rateApp(this);" class="star" data-stars="5"><img onmouseover="initChangeRatingStars(this);" src="images/star_blank.png" alt="" /></span>'
					+ ' <div class="starNumber"></div>';

	$('.starRating').each(function(){
		// add the stars
		$(this).html(starHtml);
		var rating = $(this).data('rating');
		for(var loop=1; loop <= rating; loop++)	{
			$(this).children('.star[data-stars='+loop+']').children('img').attr('src' , 'images/star.png');	
		}
		
		$(this).children('.starNumber').html('('+ rating.toPrecision(2) +')');

	});

	initChangeRatingStars();
	
}

function parseHashTag(){
	var paramsRaw = "";
	var params = {};
	try{
		paramsRaw = 
			(location.hash.split("?", 2)[1] || "").split("#")[0].split("&") || [];

		for(var i = 0; i< paramsRaw.length; i++){
			var single = paramsRaw[i].split("=");
			if(single[0])
				params[single[0]] = unescape(encodeURIComponent(single[1]));
		}
	}catch(ex){};
	
	return params;
}

/**
 * change star colors on mouse out and set to its original rating value
 * @param event e, object obj
 */
function backToOriginalStars(e , obj) {
	var currentId = $(obj).attr('id');
	$('#' + currentId).each(function(){
		// add the stars
		var rating = $(this).data('rating');
		for(var loop=1; loop <= 5; loop++)
		{
			if (loop <= rating)
				$(this).children('.star[data-stars='+loop+']').children('img').attr("src" , "images/star.png");
			else
				$(this).children('.star[data-stars='+loop+']').children('img').attr('src' , 'images/star_blank.png');
		}
	});

}

/**
 * change star colors on mouse over
 * @param object obj
 */		
function initChangeRatingStars(image) {
	obj = $(image).parent().parent();
	$(obj).children(".star").children('img').hover(function() {
		$(obj).children(".star").children('img').attr("src" , "images/star_blank.png");
		var hovered = $(this).parent().data('stars');
		while(hovered > 0) {
			$(obj).children('.star[data-stars='+hovered+']').children('img').attr("src" , "images/star.png");
			hovered--;
		}

	});
}

/**
 * rate an app by clicking on stars
 * @param object obj
 */
function rateApp(obj) {

	var current_star =  $(obj).data('stars');
	var starArea = $(obj).parent();
	var rid = $(starArea).data('id');
	var eid = $(starArea).parent().parent().children('.appImageArea').data('id');
		
	//ga('send', 'event', 'AppRating', 'click', rid, current_star);
	trackingEvent("click", "AppRating", rid, current_star);

	// check if cookie exists
	if(!$.cookie('rated'+rid))
	{
		$.getJSON(api_url_rating + '?rating='+current_star+'&id='+rid+'&callback=?', function(data) {
			if(data.message == 'SUCCESS')
				$(starArea).parent().html('<div class="highlight green">App Rated!</div>');
			else if(data.message == 'ALREADY_RATED')
				$(starArea).parent().html('<div class="highlight red">Already Rated!</div>');
			else 
				$(starArea).parent().html('<div class="highlight red">ERROR!</div>');
		});
		$.cookie('rated'+rid, true, { expires : 30 });
	} else {
		$(starArea).parent().html('<div class="highlight red">Already Rated!</div>');
	}	
	
	return false;
}

function addCustomAppIcon(){

	if($('#addInput').val().indexOf(' ') >= 0){
		$('#content #widgetList').html('<div id="noCategoryFound">No apps found.</div>');		
	}else{

		$('#noCategoryFound').remove();
		$('#addCustomApp').remove();
		
		// after the search, we replace last item
	    var htmlAddCustom = '<div class="widgetItem" id="addCustomApp"></div>';
		$('#widgetList').append(htmlAddCustom);
		
	    $('#addCustomApp').qtip({
			content: 'Click to add custom app',
			position: {
				container: $('#wrapper'),
				my: "bottom center",
				at: "top center"
			},
			show: {
				event: "mouseover"
			},
			hide: {
				event: "mouseout"
			},
			style: {
				width: 90,
				tip: true,
				classes: "qtip-light"
			}
		});
	
		$('#addCustomApp').unbind('click').click(function(){
			$(this).addClass('throbber');
			// $('#addSubmit').trigger('click');
			// $('#addForm').trigger('submit');
			var term = $('#addInput').val().trim();
			if(term.indexOf(' ') >= 0){ // there are spaces, so multiple words
				return false;
			}else if(term.indexOf('.') == -1) { // there are no dots	
				addCustomApp('www.'+term+'.com');
			}else if(term.indexOf('.') > 0){ //user entered URL
				addCustomApp(term);
			}
			return false;
		});
	}
}

$(document).mouseup(function (e){
    var container = $(".filterBox");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
        
		if($('#filterBox .current').length == 0)
			$('#filters').removeClass('current');

		// if no filter is set, remove current class
		if($('#categoryList .current').length == 0)
			$('#filter_categories').removeClass('current'); 
    }
});

if(typeof String.prototype.trim !== 'function') {
	  String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g, ''); 
	  }
}
