function getSearchParams(k){
 var p={};
 location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
 return k?p[k]:p;
}
var pagedisplayid ;
var displayGroups;
//var genres =[];
window.onload = function() {

refreshDisplayGroups();

//alert(imdbid);
}



function refreshDisplayGroups(){

   var eventrequest= $.ajax({ 
	  url: "displaygroups.json", 
	   dataType: "text"});
	  eventrequest.done(function(data){
	 displayGroups=jQuery.parseJSON(data);
	  refreshDisplayList();
	  });
}

function refreshDisplayList(){
$('#displayList').empty();
//$('#customlists').append("<div id=\"status\">Getting List Names.....</div>");

   var eventrequest= $.ajax({ 
	  url: "display_settings.json", 
	   dataType: "text"});
	  eventrequest.done(function(data){

var displayjson=jQuery.parseJSON(data);
var items = [];
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
//var name =displayjson[key].friendlyname;
 var arg =loadDisplayData(displayjson[key]);
 items.push(arg);
 
 //},0);//end settimeout
 // $('#j_4').append(arg); 
//$('#rateit'+displayjson[key].imdbid).rateit();
//delay(1);
//$('#status').text("Getting Posters, please wait.....  Found "+key).delay(10);
}
//$('#status').text("Getting Posters, Please Wait");


  $('#displayList').append( items.join('') );
$('#displayList').listview('refresh');
 $('#displayList').trigger("create");


      });
	  eventrequest.error(function(){refreshDisplayList()});
}



function loadDisplayData(display){
var displaygroupname = "";
var displayfunction="";
var layout="";
if(display.function==0){
displayfunction="Primary";
}else if(display.function==1){
displayfunction="Auxiliary";
}else if(display.function==2){
displayfunction="Info";
}

if(display.layout==0){
layout="Portrait";
}else if(display.layout==1){
layout="Landscape";
}else if(display.layout==2){
layout="Portrait (WebView)";
}else if(display.layout==3){
layout="Landscape (WebView)";
}

for (let key in displayGroups) {
 if (!displayGroups.hasOwnProperty(key)) { continue; }
if(displayGroups[key].displaygroupid==display.displaygroupid){
displaygroupname=displayGroups[key].friendlyname;
}

}
  var arg = "<li class='list'  id='" + display.displayid + "'  title='" + display.friendlyname +  "' text-align:'left'>";
                   arg +="<a href='#'  style=\"padding: 0px 0px 0px 0px !important;margin: 0px 0px 0px 0px !important;\">";
				   arg +=  "<label id=\"checklabel\" style=\"padding: 20px 0px 0px 0px !important;margin: 0px 5px 0px 0px !important;border-width: 0px 1px 0px 0px !important;height:60px;float:left;width:40px;\" data-corners='false'>";
						arg+="<div class=\"chkdiv\">";
						arg +="<fieldset class=\"chk\" id=\"foo\" data-role='controlgroup' style='height:0px !important';border:0px !important>";
             arg +=               "<input id='checkbox_"+display.displayid+"' name='"+display.displayid+"' class='item_checkbox' type='checkbox' value='false' />";
				arg +=		"</fieldset>";	
arg+="</div>";	
  arg +=		"</label>";
  arg+="<div style='text-align:left'> <h3>" + display.friendlyname + " </h3>";
  arg+="<p>DisplayGroup: " + displaygroupname + "</p>";
  arg+="<p>Layout: " + layout + "</p>";
   arg+="<p>Function: " + displayfunction + "</p>";
  arg+="</div><a class='display' href='#'></a></a></li>";
return arg;
}



String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}


 function DeleteDisplays(disp)
{
//alert(imdb+" will be deleted. Please reload the cache screen to see changes.");

    var http = new XMLHttpRequest();
    var params = "arg1=Control()";
var command="deleteDisplay("+disp.join()+")";
    http.open("POST", "ping.html?"+command, true);
    //http.setRequestHeader("Connection", "close");
    http.send(params);
		for(i=0;i<disp.length;i++){
	$('#'+disp[i]).remove();
}
}




 $(document).delegate('#confirmdelete', 'click', function() {
 //alert('confirm delete');
 //var http = new XMLHttpRequest();
 var disp = getchecked();
//var arrayLength = movies.length;
DeleteDisplays(disp);
/*
     var params = "arg1=Control()";
var command="deletePoster("+movies.join()+")";
    http.open("POST", "ping.html?"+command, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.send(params);
	for(i=0;i<movies.length;i++){
	$('#'+movies[i]).remove();
	}
	*/
	
 });
 


 
   
   $( "#popupPanel" ).on({
    popupbeforeposition: function() {
        var h = $( window ).height();

        $( "#popupPanel" ).css( "height", h );
    }
});




function getfilenamewithoutextension(filepath){
var result = "";

//extract just the filename form the full path. 

return result;
}


//$('#reload_local').bind('click', function(event){
 $(document).delegate('#adddisplay', 'click', function() {
//alert("add display not yet implemented");
addDisplay();
});


 $(document).delegate('#removecheckeddisplays', 'click', function() {
deletechecked();
});



function addDisplay(){
   var eventrequest= $.ajax({ 
	  url: "addnewdisplay.json", 
	  dataType: "text"});  
	eventrequest.done(function(data){
	    var displaydetailjson=jQuery.parseJSON(data);
		//var items = [];
		//alert("new displayid: "+displaydetailjson.displayid);
		
		
		  $('#displayList').append( loadDisplayData(displaydetailjson) );
		   $('#displayList').trigger("create");
$('#displayList').listview('refresh');
	});

}




function getchecked(){

var count = 0;
        var names = [];
        $('#displayList input:checked').each(function() {
            names.push(this.name);
			//alert(this.name);
        });
		return names;
}

function deletechecked(){
//var mylist = $('#j_4');
//var listitems = mylist.children('li').get();
var displays = getchecked();
var arrayLength = displays.length;
if(arrayLength>0){
  //  var http = new XMLHttpRequest();
//var moviestring = "";
//should probably get have a confirmation message.....
var displaynames ="";
for (var i = 0; i < arrayLength; i++) {
    //alert(myStringArray[i]);
    //remove the movie
	displaynames += "<li>"+$('#'+displays[i]).attr('title')+"</li>";
	
	//	$('#j_4').refresh();
}
//alert("The following will be deleted: "+movienames);

  $('<div>').simpledialog2({
    mode: 'blank',
    headerText: 'Confirm Delete?',
    headerClose: true,
	width: '80%',
    blankContent : 
      "<ul data-role='listview'>"+displaynames+"</ul>"+
      // NOTE: the use of rel="close" causes this button to close the dialog.
      "<table><tr><td><a rel='close' data-role='button' href='#'>Cancel</a></td>"+
	  "<td><a id=\"confirmdelete\" rel='close' data-role='button' href='#'>OK</a><td><tr></table>"
  })


}
}





var firstpoll = true;

function pollStatus(){

   setTimeout(function(){
  // this.alert("in function");
   var eventrequest= $.ajax({ 
	  url: "status.json", 
	   dataType: "text"});  
	  eventrequest.done(function(data){
	  var statusjson=jQuery.parseJSON(data);
var items = [];
for (let key in statusjson) {
 if (!statusjson.hasOwnProperty(key)) { continue; }
 parseCommand(statusjson[key]);
 }
 
 firstpoll=false;

        //Setup the next poll recursively
        pollStatus();
      });
	  eventrequest.error(function(){pollStatus()});
	  
	  
  }, 2000); //every 2 seconds
  
}

var processedStatusMessages = new Array(25); //array of length 15 to store messages
function parseCommand(com){
//alert(com.message);
if(jQuery.inArray(com.id,processedStatusMessages)<0){
//alert(com.id+" is not processed");
processedStatusMessages.shift();
processedStatusMessages.push(com.id);
if(firstpoll==false){
var messageObj = jQuery.parseJSON(com.message);
if(messageObj.action=="cached"||messageObj.action=="updated"){
		 $.notifyBar({ cssClass: "custom", html: "'"+messageObj.title+"' has been saved.",position: "bottom"});
}else if(messageObj.action=="deleted"){
		 $.notifyBar({ cssClass: "custom", html: "'"+messageObj.title+"' has been deleted.",position: "bottom"});	
}else if(messageObj.action=="trailersaved"){
		 $.notifyBar({ cssClass: "custom", html: "Trailer for '"+messageObj.title+"' has been saved.",position: "bottom"});
	
}
}

}else{
//alert(com.id+" has already been processed");
}

}





$(document).ready(function () {
    $('.slideout-menu-toggle').on('click', function(event){
    	event.preventDefault();
		event.stopImmediatePropagation();
    	// create menu variables
    	var slideoutMenu = $('.slideout-menu');
    	var slideoutMenuWidth = $('.slideout-menu').width();
    	
    	// toggle open class
    	slideoutMenu.toggleClass("open");
    	
    	// slide menu
    	if (slideoutMenu.hasClass("open")) {
	    	slideoutMenu.animate({
		    	left: "0px"
	    	});	
    	} else {
	    	slideoutMenu.animate({
		    	left: -slideoutMenuWidth
	    	}, 250);	
    	}
    });
});

$(document).ready(function () {
  //  $(":jqmData(role='editablelistview'), :jqmData(role='editable-listview')", e.target).editablelistview();
// $('#editlist').editablelistview();
    $('.slideout-menu-right-toggle').on('click', function(event){
	
    	event.preventDefault();
		event.stopImmediatePropagation();
    	// create menu variables
    	var slideoutMenu = $('.slideout-menu-right');
    	var slideoutMenuWidth = $('.slideout-menu-right').width();
    	
    	// toggle open class
    	slideoutMenu.toggleClass("open");
    	
    	// slide menu
		var width = $(document).width()- slideoutMenuWidth;
    	if (slideoutMenu.hasClass("open")) {
	    	slideoutMenu.animate({
		    	left: width 
	    	});	
    	} else {
	    	slideoutMenu.animate({
		    	left: "100%"
	    	}, 250);	
    	}
    });
});

function closeActionsMenu(){
    	var slideoutMenu = $('.slideout-menu-right');
    	var slideoutMenuWidth = $('.slideout-menu-right').width();
    	
    	// toggle open class
		if (slideoutMenu.hasClass("open")) {
    	slideoutMenu.toggleClass("open");
		}
    	
    	// slide menu
		var width = $(document).width()- slideoutMenuWidth;
    	if (slideoutMenu.hasClass("open")) {
	    	slideoutMenu.animate({
		    	left: width 
	    	});	
    	} else {
	    	slideoutMenu.animate({
		    	left: "100%"
	    	}, 250);	
    	}
}

$(window).resize(function(){
    closeActionsMenu();
});


