function getSearchParams(k){
 var p={};
 location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
 return k?p[k]:p;
}
var playlisttype =-1 ;
var displayGroups;
var recentlist;
var currentid="";
//var genres =[];
window.onload = function() {
playlisttype=getSearchParams("type");
//refreshPlaylist();
//refreshRecent();
//alert(imdbid);
//recentlist = getRecent();
pollRecent();
}

function ShowDisplayGroup(displayid)
{

    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="displaygroupid="+displayid;
window.open("displaygroupdetail.html?"+command,'_self',false);

}


$('#playist').bind('click', function(event)
{
    $(event.target).closest('.playlistitem').each(function()
    {
    	var $list = $(this).closest('.list');
		var id = $list.attr('id');
    	//var title = $list.attr('title');
              //  ShowDisplayGroup(id);	
    })
})


function getRecent(){

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

var displayjson=jQuery.parseJSON(data);
return displayjson; 

      });
	
}

function refreshRecent(displayjson){
$('#recent').empty();
//$('#customlists').append("<div id=\"status\">Getting List Names.....</div>");
/*
   var eventrequest= $.ajax({ 
	  url: "playlist.json?get(1)", 
	   dataType: "text"});
	  eventrequest.done(function(data){

var displayjson=jQuery.parseJSON(data);*/
var items = [];
var count = displayjson.length;
 $('#recent').append( "<li data-role='list-divider'>Recently Shown <span class='ui-li-count'>"+count+"</span></li>" );
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
//var name =displayjson[key].friendlyname;
 var arg =loadPlaylistData(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");


  $('#recent').append( items.join('') );
  

 
$("#recent li").last().attr("data-theme","b");//.css({ data-theme:"a"});
$('#recent').listview('refresh');
 $('#recent').trigger("create");
    //  });
	//  eventrequest.error(function(){refreshPlaylist()});
}

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

 


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

var displayjson=jQuery.parseJSON(data);
var items = [];
var count = displayjson.length;
 $('#playlist').append( "<li data-role='list-divider'>On Deck <span class='ui-li-count'>"+count+"</span></li>" );
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
//var name =displayjson[key].friendlyname;
 var arg =loadPlaylistData(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");


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


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



function loadPlaylistData(display){



  var arg = "<li class='list'  id='" + display.posterid + "'  title='" + display.title +  "' text-align:'left'>";
                   //arg +="<a href='#'  style=\"padding: 0px 0px 0px 0px !important;margin: 0px 0px 0px 0px !important;\">";

  arg+="<div style='text-align:left'> <h3>" + display.title + " </h3>";
    arg+="<div style='font-size:9px;font-weight:normal'>" + display.source + " </div>";
  arg+="</div></li>";
return arg;
}



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


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

    var http = new XMLHttpRequest();
    var params = "arg1=Control()";
var command="deleteDisplayGroup("+disp.join()+")";
  //  http.open("POST", "ping.html?"+command, true);
              //http.setRequestHeader("Connection", "close");
  //  http.send(params);
	
	
	   var eventrequest= $.ajax({ 
	  url: "ping.html?"+command, 
	  dataType: "text"});  
	eventrequest.done(function(data){
//alert(data);
var displayjson=jQuery.parseJSON(data);

for (let key in displayjson) {
if (!displayjson.hasOwnProperty(key)) { continue; }
 //alert(displayjson[key]);
  var id=displayjson[key].id;
  var name=displayjson[key].friendlyname;
  var message=displayjson[key].message;
var success = displayjson[key].success;
 if(success!=true){
 		 $.notifyBar({ cssClass: "custom", html:name+" "+message ,position: "bottom"});

 //alert();
 }
 else{
 $('#'+id).remove();
 }
 }
 


	});
	
	
	
	
	

}




 $(document).delegate('#confirmdelete', 'click', function() {
 //alert('confirm delete');
 //var http = new XMLHttpRequest();
 var disp = getchecked();
//var arrayLength = movies.length;
DeleteDisplayGroups(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('#adddisplaygroup', 'click', function() {
//alert("add display not yet implemented");
addDisplay();
});


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



function addDisplay(){
   var eventrequest= $.ajax({ 
	  url: "addnewdisplaygroup.json", 
	  dataType: "text"});  
	eventrequest.done(function(data){
	    var displaydetailjson=jQuery.parseJSON(data);
		//var items = [];
		//alert("new displayid: "+displaydetailjson.displayid);
		
		
		  $('#displayList').append( loadDisplayGroupData(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;
timeout=5;
function pollRecent(){

   setTimeout(function(){

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

var displayjson=jQuery.parseJSON(data);

 //  var newrecent = displayjson;
 var newid = displayjson[0].posterid;
   if(currentid!=newid){
   
   currentid=newid;
   refreshRecent(displayjson.reverse());
   refreshPlaylist();
   }
      });
	  eventrequest.error(function(){pollRecent()});
	  
if(firstpoll==false){timeout=5000;}
   
   
    
   
 firstpoll=false;

        //Setup the next poll recursively
        pollRecent();
      
	//  eventrequest.error(function(){pollRecent()});
	  
	  
  }, timeout); //every 5 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();
});


