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




pagedisplayid = getSearchParams("displayid"); 
refreshDisplayGroups();
refreshDisplayDetail(pagedisplayid);

//alert(imdbid);
}



function refreshDisplayGroups(){

   var eventrequest= $.ajax({ 
	  url: "displaygroups.json", 
	   dataType: "text"});
	  eventrequest.done(function(data){
	  var displaygroupjson=jQuery.parseJSON(data);
	  
	  var items = [];
for (let key in displaygroupjson) {
 if (!displaygroupjson.hasOwnProperty(key)) { continue; }
 var arg = "<option value="+displaygroupjson[key].displaygroupid+">"+displaygroupjson[key].friendlyname+"</option>";
 items.push(arg);

}
//alert(items);
$('#select-displaygroup').trigger("create");
$('#select-displaygroup').append( items.join('') ).selectmenu('refresh');
 
	  });




}






function refreshDisplayDetail(displayid){
//$('#j_4').empty();
//$('#j_4').append("<div id=\"status\">Getting Posters, please wait....</div>");


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


var displayjson=jQuery.parseJSON(data);
//alert(displayjson.title);
document.title="Details for ("+displayid+") '"+displayjson.friendlyname+"'";
//$('#textboxid').val('some value')
$('#imdbidf').val(displayid);

$('#friendlynamef').val(displayjson.friendlyname);

if(displayjson.showtrailers==true){
$('#toggleShowTrailers').val('on').trigger('create').slider('refresh');
}else{
$('#toggleShowTrailers').val('off').trigger('create').slider('refresh');
}
if(displayjson.startmaximized==true){
$('#toggleStartMaximized').val('on').trigger('create').slider('refresh');
}else{
$('#toggleStartMaximized').val('off').trigger('create').slider('refresh');
}
if(displayjson.showshowtimes==true){
$('#toggleShowtimes').val('on').trigger('create').slider('refresh');
}else{
$('#toggleShowtimes').val('off').trigger('create').slider('refresh');
}
if(displayjson.showtrivia==true){
$('#toggleTrivia').val('on').trigger('create').slider('refresh');
}else{
$('#toggleTrivia').val('off').trigger('create').slider('refresh');
}
if(displayjson.showmotionposters==true){
$('#toggleMotionposters').val('on').trigger('create').slider('refresh');
}else{
$('#toggleMotionposters').val('off').trigger('create').slider('refresh');
}

$('#webviewbutton').attr("href","/webview.html?displayid("+displayid+")");


	$('#select-layout').trigger('create');
	    $('[name=select-layout] option').filter(function() { 
        return ($(this).val() == displayjson.layout); //To select Blue
    }).prop('selected', true);
	$('#select-layout').val(displayjson.layout);
$('#select-layout').selectmenu('refresh');


	$('#select-rotation').trigger('create');
	    $('[name=select-rotation] option').filter(function() { 
        return ($(this).val() == displayjson.rotation); //To select Blue
    }).prop('selected', true);
	$('#select-rotation').val(displayjson.rotation);
$('#select-rotation').selectmenu('refresh');


	$('#select-displaygroup').trigger('create');
	    $('[name=select-displaygroup] option').filter(function() { 
        return ($(this).val() == displayjson.displaygroupid); //To select Blue
    }).prop('selected', true);
	$('#select-displaygroup').val(displayjson.displaygroupid);
$('#select-displaygroup').selectmenu('refresh');

	$('#select-function').trigger('create');
	    $('[name=select-function] option').filter(function() { 
        return ($(this).val() == displayjson.function); //To select Blue
    }).prop('selected', true);
	$('#select-function').val(displayjson.function);
$('#select-function').selectmenu('refresh');

if(displayjson.layout==2 || displayjson.layout==3){
$('#toggleStartMaximized').slider('disable');
$('#webviewbutton').removeClass("ui-disabled")
}else{
$('#toggleStartMaximized').slider('enable');
$('#webviewbutton').addClass("ui-disabled")
}


      });
	  
}

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



function test(value){
alert(value);
}




 $(document).delegate('#confirmdelete', 'click', function() {
 //alert('confirm delete');
 //var http = new XMLHttpRequest();
 var movies = getchecked();
//var arrayLength = movies.length;
DeletePoster(movies);
/*
     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();
	}
	*/
	
 });
 

 //$('#refresh_web').bind('click', function(event)
//{
 $(document).delegate('#confirmrefresh', 'click', function() {
// alert('confirm refresh web');
 var http = new XMLHttpRequest();
 var movies = pagedisplayid;
//var arrayLength = movies.length;
     var params = "arg1=Control()";
var command="refresh("+movies+")";
    http.open("POST", "ping.html?"+command, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.send(params);
 });
 
   
   $( "#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('#reload_local', 'click', function() {
refreshDisplayDetail(pagedisplayid);
});


function sendCommand(cmd)
{
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="Control("+cmd+")";
    http.open("POST", "ping.html?"+command, true);

  //  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   // http.setRequestHeader("Content-length", params.length);
  //  http.setRequestHeader("Connection", "close");

    http.onreadystatechange = function() {
        if (http.readyState == 4 && http.status == 200) {
           <!-- window.location = http.responseText;--/>
        }
    }

    http.send(params);
}

$('#restartbutton').bind('click', function(event)
{

saveData(true);
});
$('#savebutton').bind('click', function(event)
{

 saveData(false);
});





function saveData(restart){

var trailersvalue = false;
if($('#toggleShowTrailers').val()=="on"){trailersvalue=true;}

var triviavalue = false;
if($('#toggleTrivia').val()=="on"){triviavalue=true;}

var maxvalue = false;
if($('#toggleStartMaximized').val()=="on"){maxvalue=true;}

var showtimevalue = false;
if($('#toggleShowtimes').val()=="on"){showtimevalue=true;}
var motionpostervalue = false;
if($('#toggleMotionposters').val()=="on"){motionpostervalue=true;}



var savedata = {
displayid:pagedisplayid,
displaygroupid:$('#select-displaygroup').val(),
friendlyname:$('#friendlynamef').val(),
layout:$('#select-layout').val(),
rotation:$('#select-rotation').val(),
displayfunction:$('#select-function').val(),
showtrailers:trailersvalue,
showshowtimes:showtimevalue,
startmaximized:maxvalue,
showtrivia:triviavalue,
showmotionposters:motionpostervalue
};
//alert(JSON.stringify(savedata));
//var detailjson=objectifyForm($('#detailform').serializeArray());


//alert(JSON.stringify(detailjson));
 //var data = {'bob':'foo','paul':'dog'};
$.ajax({
   url: "updatedisplaysettings.json",
   type: 'POST',
   contentType:'application/json',
   data: JSON.stringify(savedata),
   dataType:'json',
   success: function(data){
     //On ajax success do this
     //alert(data);
	 if(data=="Success"){
	// alert("data has been saved");
	 		 $.notifyBar({ cssClass: "custom", html: "Data for '"+savedata.friendlyname+"' ("+savedata.displayid+") has been saved.",position: "bottom"});

	 //reload the json for this movie
	 refreshDisplayDetail(pagedisplayid);
	 if(restart==true){
	 sendCommand("restart");
	 }
	// alert("data refreshed for "+imdbid);
	 }
      },
	  error: function(XMLHttpRequest, textStatus, errorThrown){
	  	 		 $.notifyBar({ cssClass: "custom", html: "Error updating'"+savedata.friendlyname+"' ("+savedata.displayid+"). "+errorThrown,position: "bottom"});

	 // alert(textStatus+" "+errorThrown);
	  }
 });

}








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();
});


