function getSearchParams(k){
 var p={};
 location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
 return k?p[k]:p;
}
var pageimdbid ;
//var genres =[];
window.onload = function() {
//setTimeout(function(){window.scrollTo(0, 1);}, 100);
//refreshPosterList("");
//alert("test");
    $('img.caption').captionjs({
        'class_name'      : 'captionjs', // Class name for each <figure>
        'schema'          : true,        // Use schema.org markup (i.e., itemtype, itemprop)
        'mode'            : 'default',   // default | stacked | animated | hidden (deprecated: hide)
        'debug_mode'      : false,       // Output debug info to the JS console
        'force_dimensions': true,        // Force the dimensions in case they cannot be detected (e.g., image is not yet painted to viewport)
        'is_responsive'   : false,       // Ensure the figure and image change size when in responsive layout. Requires a container to control responsiveness!
        'inherit_styles'  : true        // Have the caption.js container inherit box-model properties from the original image
    });


pageimdbid = getSearchParams("imdbid"); 
refreshCustomLists();
refreshGenreList();
refreshHeaderList();
refreshPosterDetail(pageimdbid);

//alert(imdbid);
}



function refreshGenreList(){
$('#select-genre').empty();
   var eventrequest= $.ajax({ 
	  url: "genrelist.json", 
	   dataType: "text"});
	  eventrequest.done(function(data){

var displayjson=jQuery.parseJSON(data);
var items = [];
var blankgenre = "<option value=''></option>";
 items.push(blankgenre);
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
var name =displayjson[key];
var arg = "<option value="+name+">"+name+"</option>";
 items.push(arg);
}
$('#select-genre').trigger("create");
$('#select-genre').append( items.join('') ).selectmenu('refresh');
      });						
}

function refreshHeaderList(){
$('#select-header').empty();
   var eventrequest= $.ajax({ 
	  url: "headerlist.json", 
	   dataType: "text"});
	  eventrequest.done(function(data){

var displayjson=jQuery.parseJSON(data);
var items = [];
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
// alert(name);
var name =displayjson[key];
var arg = "<option value="+name.Name+">"+name.Name+"</option>"
 items.push(arg);
}
$('#select-header').trigger("create");
$('#select-header').append( items.join('') ).selectmenu('refresh');
      });						
}


var postercount = 0;

function ShowPoster(imdb)
{
    var http = new XMLHttpRequest();

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

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
/*
    http.onreadystatechange = function() {
        if (http.readyState == 4 && http.status == 200) {
           <!-- window.location = http.responseText;--/>
        }
    }*/

    http.send(params);
}

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

   var eventrequest= $.ajax({ 
	  url: "customlists.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];
 var arg = "<li><a class=\"customlistselection\" id=\""+name+"\" href=\"#\" >"+name+"</a></li>";
 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");


  $('#customlists').append( items.join('') );
//$('#customlists').listview('refresh');
 $('#customlists').trigger("create");
bindcustomlist();




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

function bindcustomlist() {
$('.customlistselection').bind('click', function(event) {
//$(".customlistselection").click(function (event) {
//alert("custom list: "+this.id);
//get currently selected
var listname = this.id;
event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
closeActionsMenu();

var movies = pageimdbid;
//var arrayLength = movies.length;
//should probably get have a confirmation message.....
var movienames ="";
//for (var i = 0; i < arrayLength; i++) {
    //alert(myStringArray[i]);
    //remove the movie
	//movienames += "<li>"+$('#'+movies[i]).attr('title')+"</li>";
	
	//	$('#j_4').refresh();
//}
//alert("The following will be deleted: "+movienames);

  $('<div>').simpledialog2({
    mode: 'blank',
    headerText: 'Add to List?',
    headerClose: true,
	width: '80%',
    blankContent : "<h3>"+listname+"</h3>"+
    //  "<ul data-role='listview'>"+movienames+"</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=\"confirmaddtolist\" name=\""+listname+"\" rel='close' data-role='button' href='#'>OK</a><td><tr></table>"
  })




  });
}

$('#userratingf').on('change', function (event) {
var value = $('#userratingf').val();
var max = $('#user_star_rating').attr('data-rateit-max');
var min = $('#user_star_rating').attr('data-rateit-min');
if(value>max){
value=max;
$('#userratingf').val(value);
}
if(value<min)
{
value=min;
$('#userratingf').val(value);
}
//alert("user score value "+value);
$('#user_star_rating').rateit('value',value);
});

$('#tmdbratingf').on('change', function (event) {
var value = $('#tmdbratingf').val();
var max = $('#web_star_rating').attr('data-rateit-max')*2;
var min = $('#web_star_rating').attr('data-rateit-min');
if(value>max){
value=max;
$('#tmdbratingf').val(value);
}
if(value<min)
{
value=min;
$('#tmdbratingf').val(value);
}
//alert("user score value "+value);
$('#web_star_rating').rateit('value',value/2);
});

$('#user_star_rating').rateit();
    $("#user_star_rating").bind('rated', function (event, value) { 
	//alert("value: "+value+" ,id: "+$(this).attr('data_imdbid'));
//	setRating(pageimdbid,value);
//alert("set user rating: " +value);
$('#userratingf').val(value);
	});
	
    $("#user_star_rating").bind('reset', function () { 
	//alert("reset user rating");
//	setRating($(this).attr('data_imdbid'),"0"); 
$('#userratingf').val(0);
	});
	
	$('#web_star_rating').rateit();
    $("#web_star_rating").bind('rated', function (event, value) { 
	//alert("value: "+value+" ,id: "+$(this).attr('data_imdbid'));
//	setRating(pageimdbid,value);
$('#tmdbratingf').val(value*2);
//alert("set web rating: " +value);
	});
    $("#web_star_rating").bind('reset', function () { 
	//alert("reset web rating");
	$('#tmdbratingf').val(0);
//	setRating($(this).attr('data_imdbid'),"0"); 
	});

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


   var eventrequest= $.ajax({ 
	  url: "rawposterdetails.json?getPosterDetails("+imdbid+")", 
	   dataType: "text"});
	  eventrequest.done(function(data){


var displayjson=jQuery.parseJSON(data);
//alert(displayjson.title);
document.title="Details for "+imdbid+" '"+displayjson.title+"'";
//$('#textboxid').val('some value')
$('#imdbidf').val(imdbid);
$('#taglinef').val(displayjson.tagline);
$('#titlef').val(displayjson.title);
$('#yearf').val(displayjson.year);
$('#webpagef').val(displayjson.TmdbHomepage);
$('#summaryf').val(displayjson.plotOutline);
$('#plotf').val(displayjson.plot);
$('#ratingf').val(displayjson.mpaaRating);

var userrating=displayjson.userRating;

$('#userratingf').val(userrating);
//$('#user_star_rating_backing').val(userrating);

$('#user_star_rating').rateit('value',userrating);
var webrating=displayjson.TmdbVoteAverage / 2;
$('#web_star_rating').rateit('value',webrating);


$('#tmdbratingf').val(displayjson.TmdbVoteAverage);
$('#genref').val(displayjson.genre);
$('#runtimef').val(displayjson.runtime);

$("#logoIMG").attr("src", displayjson.logo);
$("#posterIMG").attr("src", displayjson.poster);

$("#IMGrating").attr("src", displayjson.mpaaIMG);
$("#IMGrating").attr("savevalue", displayjson.mpaaRating);

$("#IMGresolution").attr("src", displayjson.resolutionIMG);
$("#IMGresolution").attr("savevalue", displayjson.resolution);

$("#IMGaspectratio").attr("src", displayjson.aspectIMG);
$("#IMGaspectratio").attr("savevalue", displayjson.aspectRatio);

$("#IMGstudio").attr("src", displayjson.studioIMG);
$("#IMGstudio").attr("savevalue", displayjson.studio);

$("#IMGaudio").attr("src", displayjson.audioIMG);
var audiocodec = displayjson.audioCodec;
var audiochan = displayjson.audioChanels;
if(audiochan>0){audioCodec+=audiochan;}
$("#IMGaudio").attr("savevalue", audiocodec);

var motionpath = displayjson.motionPosterPath;
//alert(motionpath);
if(motionpath.toLowerCase().indexOf(".gif") > -1){
$("#motionposterIMG").attr("src", motionpath);
}else if(motionpath.toLowerCase().indexOf(".mp4") > -1){
//alert(motionpath);
$("#mpsource").attr("src", motionpath);
 document.getElementById("mp_video").load();
}
/*
    $('#select-genre option').filter(function() { 
        return ($(this).text() == displayjson.genre);
    }).prop('selected', true);
	*/
	$('#select-genre').trigger('create');
	    $('[name=select-genre] option').filter(function() { 
        return ($(this).text() == displayjson.genre); //To select Blue
    }).prop('selected', true);
	$('#select-genre').val(displayjson.genre);
	
$('#select-genre').selectmenu('refresh');


$("#backgroundIMG").attr("src", displayjson.background);
$("#bannerIMG").attr("src", displayjson.banner);
$("#discIMG").attr("src", displayjson.discImage);

$("#trailersource").attr("src", displayjson.trailerURL);
 document.getElementById("trailer_video").load();
 
 	  //cast
	//  alert(displayjson.cast.toString());
	 // var arrayLength = displayjson.cast.length;
	 // alert(arrayLength);
	  
	  
	  $('#castlist').listview().listview('refresh');
$('#castlist').empty();
 
var items = [];
/// do stuff 

var castindex=0;

	//  alert(displayjson.cast.items.length);
	  
	  
	  for (var prop in displayjson.cast) {
  if (displayjson.cast.hasOwnProperty(prop)) { 
  // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
   // alert("prop: " + prop + " value: " + displayjson.cast[prop])
   	  var actor = prop;
	  var character=displayjson.cast[prop];
	  var index="cast_"+castindex;
	  var castline = casttemplate;
	  castline = castline.replace("{{castindex}}",index);
	    castline = castline.replaceAll("{{castindexid}}",index);
	  castline =castline.replace("{{actor}}",actor);
	  	  castline =castline.replace("{{character}}",character);
	  //	$('#castlist').listview.  
 //$('#castlist').append(castline);
  items.push(castline);
  castindex=castindex+1;
  }
}
//alert(castindex);
if(castindex==0){
var castline = casttemplate.replace("{{castindex}}","cast_0");
castline = castline.replaceAll("{{castindexid}}","cast_0");
castline = castline.replace("{{actor}}","");
castline = castline.replace("{{character}}","");
$('#castlist').append(castline);
$('#castlist').trigger('create');
$('#castlist').listview().listview('refresh');
}
$('#castlist').append( items.join('') ).listview('refresh');
$('#castlist').trigger("create"); 


 
      });
	  

	  
	//  eventrequest.error(function(){refreshPosterList("")});
}

var casttemplate = "<li id='{{castindex}}' class='ui-field-contain castli'><table width='100%' class='casttable'><tr><td><div data-role='fieldcontain' class='castdata'>Actor<input class='actor' value='{{actor}}' data-theme='a' /></div></td><td><div data-role='fieldcontain' class='castdata'>Character<input value='{{character}}' class='character' data-theme='a' /></div></td><td><div data-role='controlgroup' data-mini='true' data-type='horizontal' ><input onClick=\"addcast('{{castindexid}}')\" type='button' value='Add' data-icon='plus' data-iconpos='notext'><input type='button' value='Remove' onClick=\"removecast('{{castindexid}}')\" data-icon='delete' data-iconpos='notext'><input type='button' onClick=\"moveCastUp('{{castindexid}}')\" value='up' data-icon='arrow-u' data-iconpos='notext'><input type='button' onClick=\"moveCastDown('{{castindexid}}')\" value='down' data-icon='arrow-d' data-iconpos='notext'></div></td></tr></table></li>";

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

function moveCastUp(itemid) {
    $before = $('#'+itemid).prev();
	if (typeof $before != 'undefined'){
    $('#'+itemid).insertBefore($before);
	}
}

function moveCastDown(itemid) {
    $after = $('#'+itemid).next();
	if (typeof $after != 'undefined'){
    $('#'+itemid).insertAfter($after);
	}
}

$('.addcast1').bind('click', function(event) {
var castid=$(this).closest('li').attr('id');
//alert('add cast: '+castid);
});
function removecast(castid){
$('#'+castid).remove();
$('#castlist').listview().listview('refresh');
}

function addcast(castid){
//alert(castid);
//var castid=$(this).closest('li').attr('id');
//alert('add cast: '+castid);
var l = $('#castlist').children().length;
var castline = casttemplate.replace("{{castindex}}","cast_"+l);
castline = castline.replaceAll("{{castindexid}}","cast_"+l);
castline = castline.replace("{{actor}}","");
castline = castline.replace("{{character}}","");
$('#'+castid).after(castline);
$('#castlist').trigger('create');
$('#castlist').listview().listview('refresh');
}

function sortDsc(sortby){
var mylist = $('#j_4');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
//var sortby = "title";
//sortby = "rateit";
//sortby = "rottentomatoes";
//sortby = "dateadded";
if(sortby=="rateit"){
var $rating = $(a).closest('.rateit');
//alert($rating.attr('data-rateit-value'));
//alert($(a).attr('data-rating'))
   return $(b).attr('sort-rating').localeCompare($(a).attr('sort-rating'));
}else if(sortby=="rottentomatoes"){
   return $(b).attr('sort-rt').localeCompare($(a).attr('sort-rt'));
}else if(sortby=="dateadded"){
   return $(b).attr('sort-date').localeCompare($(a).attr('sort-date'));
}else{
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
  }
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
}


function sortAsc(sortby){
var mylist = $('#j_4');
var listitems = mylist.children('li').get();
listitems.sort(function(b, a) {
//var sortby = "title";
//sortby = "rateit";
//sortby = "rottentomatoes";
//sortby = "dateadded";
if(sortby=="rateit"){
var $rating = $(a).closest('.rateit');
//alert($rating.attr('data-rateit-value'));
//alert($(a).attr('data-rating'))
   return $(b).attr('sort-rating').localeCompare($(a).attr('sort-rating'));
}else if(sortby=="rottentomatoes"){
   return $(b).attr('sort-rt').localeCompare($(a).attr('sort-rt'));
}else if(sortby=="dateadded"){
   return $(b).attr('sort-date').localeCompare($(a).attr('sort-date'));
}else{
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
  }
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
}

function getchecked(){
//var mylist = $('#j_4');
//var listitems = mylist.children('li').get();
var count = 0;
        var names = [];
        $('#j_4 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 movies = getchecked();
var arrayLength = movies.length;
if(arrayLength>0){
  //  var http = new XMLHttpRequest();
//var moviestring = "";
//should probably get have a confirmation message.....
var movienames ="";
for (var i = 0; i < arrayLength; i++) {
    //alert(myStringArray[i]);
    //remove the movie
	movienames += "<li>"+$('#'+movies[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'>"+movienames+"</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>"
  })


}
}

function opensearch(){
//window.location.assign('search.html');

  $(document).simpledialog2({
    mode: 'blank',
    headerText: 'Add Poster',
    headerClose: true,
	width: '100%',
	//height:'100px',
	 //   dialogAllow: true,
 //  dialogForce: true,
    blankContent : 
	"<body><div data-role='page'></div></body>"+
	                "<div class=\"mobilegrid2_wrapper\">"+
					"				<div>"+
"<fieldset name= 'searchselect' id='searchselect' data-role=\"controlgroup\" data-type=\"horizontal\" data-mini=\"true\" align =\"center\">"+
        "<input class ='searchtyperadio' type=\"radio\" name=\"search-choice\" id=\"search-choice-movies\" value=\"movies\" checked=\"checked\">"+
        "<label for=\"search-choice-movies\">Movies</label>"+
		
        "<input class ='searchtyperadio' type=\"radio\" name=\"search-choice\" id=\"search-choice-tv\" value=\"tvshows\">"+
        "<label for=\"search-choice-tv\">TV Shows</label>"+
		
        "<input class ='searchtyperadio' type=\"radio\" name=\"search-choice\" id=\"search-choice-games\" value=\"games\">"+
        "<label for=\"search-choice-games\">Games</label>"+
"</fieldset>"+
"</div>"+
 "                   <table id=\"j_46\" width='100%'  "+
  "                  cellspacing=0>"+
                          "      <tr>"+
                                   " <td id=\"j_49\"  colspan=1 rowspan=1>"+
                                    "    <div class=\"cell-wrapper\">"+
                                     "       <div data-role=\"fieldcontain\" class=\"mobiletextinput1\">"+
                                      "          <input type=\"search\"  id=\"j_90\" value=\"\" placeholder=\"Search by Title\""+
                                       "         tabIndex=\"1\" data-theme='c' class=' mobiletextinput1 ' />"+
                                        "    </div>"+
                                        "</div>"+
                                   " </td>"+
                                "</tr>"+
                    "</table>"+
                "</div>"+
      //"<div id=\"searchscrolldiv\" style=\"height:85%;overflow-y:scroll;overflow-x:hidden\" ><ul id=searchresults data-role='listview'><li>Sample Title</li></ul></div>"+
      // NOTE: the use of rel="close" causes this button to close the dialog.
      "<table width='100%'><tr><td><a rel='close' data-role='button'  data-mini='true' href='#'>Cancel</a></td>"+
	  "<td><a id=\"search\" data-role='button'  data-mini='true' href='#'>Search</a><td><tr></table>"+
	  
	                      "<ul id='searchresults' data-role='listview' class=' mobilelist1 ' "+
                   " data-filter='false' data-theme='a'"+
                    "data-divider-theme='b' data-count-theme='b'  data-split-icon='plus' data-split-theme='a'>"
	      //  "<ul id=searchresults data-role='listview'><li>Sample Title</li></ul>"

  })



}

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

  $('<div>').simpledialog2({
    mode: 'blank',
    headerText: 'Confirm Delete & Blacklist?',
    headerClose: true,
	width: '80%',
    blankContent : 
      "<ul data-role='listview'>"+movienames+"</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=\"confirmdeldisable\" rel='close' data-role='button' href='#'>OK</a><td><tr></table>"
  })


}
}


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

function refreshchecked(){
var movies = pageimdbid;
//var arrayLength = movies.length;
//if(arrayLength>0){
//should probably get have a confirmation message.....
//var movienames ="";
//for (var i = 0; i < arrayLength; i++) {
	//movienames += "<li>"+$('#'+movies[i]).attr('title')+"</li>";
//}
  $('<div>').simpledialog2({
    mode: 'blank',
    headerText: 'Confirm Data Refresh?',
    headerClose: true,
	width: '80%',
    blankContent : 
  //    "<ul data-role='listview'>"+movienames+"</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=\"confirmrefresh\" rel='close' data-role='button' href='#'>OK</a><td><tr></table>"
  })
//}
}

/*
$(document).delegate('#opendialog', 'click', function() {
  // NOTE: The selector can be whatever you like, so long as it is an HTML element.
  //       If you prefer, it can be a member of the current page, or an anonymous div
  //       like shown.
  $('<div>').simpledialog2({
    mode: 'blank',
    headerText: 'Some Stuff',
    headerClose: true,
    blankContent : 
      "<ul data-role='listview'><li>Some</li><li>List</li><li>Items</li></ul>"+
      // NOTE: the use of rel="close" causes this button to close the dialog.
      "<a rel='close' data-role='button' href='#'>Close</a>"
  })
})*/

 $(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();
	}
	*/
	
 });
 
  $(document).delegate('.searchtyperadio', 'change', function() {
 //$(".searchtyperadio").change(function (event) {
event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
//alert("empty");
$('#searchresults').empty();
executesearch();
});
 
function executesearch(){
  var searchtype = $("input[name='search-choice']:checked").val();
var queryurl = "searchResult.json";

if(searchtype=="movies"){
queryurl = "movieSearchResult.json";
}else if(searchtype=="games"){
queryurl = "gameSearchResult.json";
}else if(searchtype=="tvshows"){
queryurl = "tvSearchResult.json";
}
//alert(queryurl);
 var text = $('#j_90').val();
 //$('#searchresults').clear();
 $('#searchresults').empty();
 if(text.length>1){
$('#searchresults').append("<div id=\"searchstatus\">Searching, please wait.....</div>");
    var eventrequest= $.ajax({ 
	  url: queryurl+"?id("+text+")", 
	   dataType: "text"});
	  eventrequest.done(function(data){

var displayjson=jQuery.parseJSON(data);
if(displayjson.length==0){
 $('#searchresults').append("<div id=\"searchstatus\">No Results.</div>");

}
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
//setTimeout(function() {
 if(displayjson[key].id!=null){
 var movie = "<li class=\"movie\"  id=\"" + displayjson[key].id + "\"  title=\"" + displayjson[key].title + "\"><a class=\"poster\" href=\"#\"><img data-original=\"" + displayjson[key].image+ "\" src=\""+displayjson[key].image+"\" height=\"100\" class=\"lazy\"/> <h3>" + displayjson[key].title + " </h3></a><a href='#' class='confirm_add' >Add Poster</a></li>";
  $('#searchresults').append(movie);
   // $('#searchresults').append("<li>"+displayjson[key].id+" "+displayjson[key].title+"</li>");

 }
 }
 $('#searchstatus').text("");
 $('#searchresults').listview('refresh');
// $('#'+posterobj.imdbid).closest('.rateit').rateit();
 $('#searchresults').trigger("create");
 $('#searchresults').bind('click', function(event)
{
event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
    $(event.target).closest('.confirm_add').each(function()
    {
    	// Get ID from city
    	var $movie = $(this).closest('.movie');
		var id = $movie.attr('id');
    	var title = $movie.attr('title');
 $.notifyBar({ cssClass: "custom", html: "'"+title+"' will be added.",position: "bottom"});
    	// Do any AJAX request to tell the server to delete the city
//answer = confirm(" '" + title+"' will be added to the cache.");
addPoster(id);
/*
            if (answer){
                
				
return true;
                //window.location.href = loc;
            }else{
                event.preventDefault();
                return false;
                //window.location.href = window.location.href;
            }
			*/
    	
    })
	



})
 
});
 }else{
 $('#searchresults').append("<div id=\"searchstatus\">No Results.</div>");
 }
 }

  $(document).delegate('#search', 'click', function() {
 //alert('confirm delete');
 //var http = new XMLHttpRequest();
//alert("search");
executesearch();
 
 //$('#searchresults').append("<li>"+text+"</li>");


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

 
 function addPoster(imdb)
{
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="addPoster("+imdb+")";
    http.open("POST", "ping.html?"+command, true);
 //http.setRequestHeader("Connection", "close");
 //  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  /*   http.setRequestHeader("Content-length", params.length);
   

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

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

    var http = new XMLHttpRequest();
    var params = "arg1=Control()";
var command="deletePoster("+movies.join()+")";
    http.open("POST", "ping.html?"+command, true);
    //http.setRequestHeader("Connection", "close");
    http.send(params);
		for(i=0;i<movies.length;i++){
	$('#'+movies[i]).remove();
}
}
 
  $(document).delegate('#confirmdeldisable', 'click', function() {
 //alert('confirm delete');
 var http = new XMLHttpRequest();
 var movies = getchecked();
var arrayLength = movies.length;
     var params = "arg1=Control()";
var command="disableAndDeletePoster("+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 = pageimdbid;
//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);
 });
 
 $(document).delegate('#confirmaddtolist', 'click', function(event) {
 var listname = event.currentTarget.name;
 //alert('confirm addtolist: '+listname);
 var http = new XMLHttpRequest();

 var movies = pageimdbid;
     var params = "arg1=Control()";
var command="addToList("+listname+","+movies+")";
    http.open("POST", "ping.html?"+command, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.send(params);
	// alert('delete complete');
 });
 


	 
  

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

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


$(".sortradio").change(function (event) {
event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
if ($("#radio-choice-t-6a").prop("checked")) {
		if($("#radio-choice-t-6a").hasClass("order-asc")){
		$("#radio-choice-t-6a").removeClass("order-asc");
					$("#radio-choice-t-6a-icon").removeClass("down");
			$("#radio-choice-t-6a-icon").addClass("up");
			sortDsc("title");

	//$( "#sortgroup" ).buttonset();
   // $( "#radio-choice-t-6a" ).button( "option", "icons", {primary:'ui-icon-gear',secondary:'ui-icon-triangle-1-s'} );
			}else{
			//$("#radio-choice-t-6a").removeClass("order-dsc");
			$("#radio-choice-t-6a").addClass("order-asc");

							$("#radio-choice-t-6a-icon").removeClass("up");
			$("#radio-choice-t-6a-icon").addClass("down");
			sortAsc("title");
			}
        }
else if($("#radio-choice-t-6b").prop("checked")){
     // $('#r1edit:input').attr('disabled', 'disabled');
	// alert("sort by rating");
	//sortDsc("rateit");
	
			if($("#radio-choice-t-6b").hasClass("order-asc")){
		$("#radio-choice-t-6b").removeClass("order-asc");
					$("#radio-choice-t-6b-icon").removeClass("down");
			$("#radio-choice-t-6b-icon").addClass("up");
			//sortDsc("title");
			sortAsc("rateit");
			}else{
			//$("#radio-choice-t-6a").removeClass("order-dsc");
			$("#radio-choice-t-6b").addClass("order-asc");
										$("#radio-choice-t-6b-icon").removeClass("up");
			$("#radio-choice-t-6b-icon").addClass("down");
			//sortAsc("title");
			sortDsc("rateit");
			}
			
        }
		else if($("#radio-choice-t-6c").prop("checked")){
     // $('#r1edit:input').attr('disabled', 'disabled');
	// alert("sort by rotten tomatoes");
	
				if($("#radio-choice-t-6c").hasClass("order-asc")){
		$("#radio-choice-t-6c").removeClass("order-asc");
					$("#radio-choice-t-6c-icon").removeClass("down");
			$("#radio-choice-t-6c-icon").addClass("up");
			//sortDsc("title");
			//sortDsc("rateit");
			sortAsc("rottentomatoes");
			}else{
			//$("#radio-choice-t-6a").removeClass("order-dsc");
			$("#radio-choice-t-6c").addClass("order-asc");
										$("#radio-choice-t-6c-icon").removeClass("up");
			$("#radio-choice-t-6c-icon").addClass("down");
			//sortAsc("title");
			//sortAsc("rateit");
			sortDsc("rottentomatoes");
			}
	
        }
		else if($("#radio-choice-t-6d").prop("checked")){
     // $('#r1edit:input').attr('disabled', 'disabled');
	// alert("sort by date added");
	 
	 				if($("#radio-choice-t-6d").hasClass("order-asc")){
		$("#radio-choice-t-6d").removeClass("order-asc");
					$("#radio-choice-t-6d-icon").removeClass("down");
			$("#radio-choice-t-6d-icon").addClass("up");
			//sortDsc("title");
			//sortDsc("rateit");
			//sortDsc("rottentomatoes");
			sortAsc("dateadded");
			}else{
			//$("#radio-choice-t-6a").removeClass("order-dsc");
			$("#radio-choice-t-6d").addClass("order-asc");
										$("#radio-choice-t-6d-icon").removeClass("up");
			$("#radio-choice-t-6d-icon").addClass("down");
			//sortAsc("title");
			//sortAsc("rateit");
			//sortAsc("rottentomatoes");
			sortDsc("dateadded");
			}
	 
	 
        }
                    });
					
function ShowOptions(imdb)
{
    var http = new XMLHttpRequest();
    var params = "arg1=Control(Previous)";
	var command="posterOptions("+imdb+")";
	window.open("PosterOptions.html?"+command,'_self',false);
}
$('#add_poster').bind('click', function(event)
{

event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
closeActionsMenu();
opensearch();
})

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

event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
//getchecked();
//alert("test");
//$( "#popupNested" ).popup( "close" )
closeActionsMenu();
deletechecked();
})

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

event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
//getchecked();
//alert("test");
//$( "#popupNested" ).popup( "close" )
closeActionsMenu();
//deletechecked();
deldisablechecked();
})


$('#refresh_web').bind('click', function(event)
{
event.stopPropagation();
event.preventDefault();
event.stopImmediatePropagation();
closeActionsMenu();
refreshchecked();
})






$('#j_4').bind('click', function(event)
{
		//event.stopPropagation();
//event.preventDefault();
//event.stopImmediatePropagation();
    $(event.target).closest('.confirm_delete').each(function()
    {
    	var $movie = $(this).closest('.movie');
		var id = $movie.attr('id');
    	var title = $movie.attr('title');
		var result = true;
		ShowOptions(id);

    	return result;
    })
})

$('#j_4').bind('click', function(event)
{
    $(event.target).closest('.movie').each(function()
    {
//	alert("show movie");
    	var $movie = $(this).closest('.movie');
		var id = $movie.attr('id');
    	var title = $movie.attr('title');
               // ShowPoster(id);
    })
})

$('.image-edit-button').bind('click', function(event)
{
var current="";

if($(this).siblings('img').length>0){
//alert('this is an image edit');
current =$(this).siblings('img').attr('src');
   $( "#IMGedit" ).attr('edittype','img');

}else if($(this).siblings('video').length>0){
//alert('this is a video edit');
current =$(this).siblings('video').children("source").attr("src");
   $( "#IMGedit" ).attr('edittype','video');
}
var etype = $(this).attr('edittype')
   $( "#IMGedit" ).attr('edittype',etype);

	//alert(videocurrent);
       var refer = ($(this).attr('refer'));
	   var altsearch = ($(this).attr('altsearch'));
   $( "#IMGedit" ).attr('referedby',refer);
   $( "#IMGedit" ).attr('altsearch',altsearch);
   var editname = ($(this).attr('name'));
   var filetypes = ($(this).attr('filetypes'));
   $( "#IMGedit" ).find('.currentval').text("Current: "+current);
$( "#IMGedit" ).find('h3').text(editname);

  $('#mediaStoreList').listview().listview('refresh');
$('#mediaStoreList').empty();

  $('#alternateTmdbList').listview().listview('refresh');
$('#alternateTmdbList').empty();


	     var eventrequest= $.ajax({ 
	  url: "mediacache.json?types("+filetypes+")", 
	   dataType: "text"});
	  eventrequest.done(function(data){

var displayjson=jQuery.parseJSON(data);
//alert('parsed');
var items = [];
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
var name =displayjson[key].Name;
var imagepath = displayjson[key].ImagePath;
var valuepath = displayjson[key].Value;
 var arg = "<li class='altimage'><label style='align:right; border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;'><fieldset data-role='controlgroup'> ";
arg+="<table width='100%'><tr><td><input type='radio'  name='radio-choice-imagestore' id='radiochoice_"+name+"' sel='"+valuepath+"'> ";  
arg+="<img  class='mediastorelistimage'  src=\""+imagepath+"\" /></td><td style='text-align:right;'>"+name+"</td></tr></table></fieldset></label></li>";
 
 
 items.push(arg);

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

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

var displayjson=jQuery.parseJSON(data);
//alert('parsed');
var items = [];
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
var name =displayjson[key].Name;
var imagepath = displayjson[key].ImagePath;
var valuepath = displayjson[key].Value;
 var arg = "<li class='altimage'>";
             arg +="<a href='#'  style=\"padding: 0px 0px 0px 0px !important;margin: 0px 0px 0px 0px !important;\">";
 arg+="<label style='align:right; border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;'><fieldset data-role='controlgroup'> ";
arg+="<table width='100%'><tr class='medialistrow'><td><input type='radio'  name='radio-choice-websearch' id='radiochoice_"+name+"' sel='"+valuepath+"'> ";  
arg+="<img  class='mediastorelistimage'  src=\""+imagepath+"\" style='height:145px;float:left;padding-right:10px;' /></td><td style='text-align:right;'>"+name+"</td></tr></table></fieldset></label></a></li>";


 
 items.push(arg);

}
 $('#alternateTmdbList').append( items.join('') ).listview('refresh');
$('#alternateTmdbList').trigger("create"); 
	  });	  
	  
	  
	  
$( "#IMGedit" ).popup( "open" );

})


$('.image-list-edit-button').bind('click', function(event)
{
   var current =$(this).siblings('img').attr('src');
  // var type = =$(this).siblings('img').attr('src');
  // var editid = ($(this).attr('id'));
  // alert(editid);
 
   var editname = ($(this).attr('name'));
    var refer = ($(this).attr('refer'));
   $( "#IMGlistedit" ).attr('referedby',refer);
   $( "#IMGlistedit" ).attr('editname',editname);
   $( "#IMGlistedit" ).find('.currentval').text("Current: "+current);
$( "#IMGlistedit" ).find('h3').text(editname);
 // $('#mediaFlagList').listview('refresh');

/*
   var eventrequest= $.ajax({ 
	  url: "posterdetails.json?getPosterDetails("+imdbid+")", 
	   dataType: "text"});
	  eventrequest.done(function(data){


var displayjson=jQuery.parseJSON(data);



      });
	  */
	  
	  //////////  

currentpage=0;
$('#mediaflagcount').text("Loading...");
$('#mediaflagsearch').val("");
$('#page_index').text("Page "+(currentpage+1)+" of "+totalpages);
$( "#IMGlistedit" ).popup( "open" );
refreshMediaFlagList($('#IMGlistedit').attr('editname'), $('#mediaflagsearch').val(),currentpage,itemsperpage);

	  

})



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

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

var cast={};
var listItems = $("#castlist li");
listItems.each(function(idx, li) {
    var act = $(li).find('.actor').val();
 var chara = $(li).find('.character').val();
    // and the rest of your code


var actor = act;
var character = chara;
cast[ actor ] = character;
});

var savedata = {
imdbid:pageimdbid,
title:$('#titlef').val(),
mpaaRating:$('#ratingf').val(),
poster:$('#posterIMG').attr('src'),
background:$('#backgroundIMG').attr('src'),
banner:$('#bannerIMG').attr('src'),
disc:$('#discIMG').attr('src'),
logo:$('#logoIMG').attr('src'),
trailer:$('#trailersource').attr('src'),
userRating:$('#userratingf').val(),
year:$('#yearf').val(),
aspectRatio:$('#IMGaspectratio').attr('savevalue'),
tagline:$('#taglinef').val(),
webpage:$('#webpagef').val(),
summary:$('#summaryf').val(),
plot:$('#plotf').val(),
mpaaimage:$('#IMGrating').attr('savevalue'),
audioCodec:$('#IMGaudio').attr('savevalue'),
resolution:$('#IMGresolution').attr('savevalue'),
studio:$('#IMGstudio').attr('savevalue'),
motionposter:$('#mpsource').attr('src'),
userheader:$('#select-header').val(),
runtime:$('#runtimef').val(),
genre:$('#select-genre').val(),
RTcriticRating:"",
RTaudienceRating:"",
RTcriticRating:"",
RTaudienceScore:"",
RTcriticScore:"",
TmdbVoteAverage:$('#tmdbratingf').val(),
locked:"",
cast:cast
};
//alert(JSON.stringify(savedata));
//var detailjson=objectifyForm($('#detailform').serializeArray());
$("#trailersource").attr("src", "");
document.getElementById("trailer_video").load();
$("#mpsource").attr("src", "");
document.getElementById("mp_video").load();
//alert(JSON.stringify(detailjson));
 //var data = {'bob':'foo','paul':'dog'};
$.ajax({
   url: "updatedetails.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.title+"' ("+savedata.imdbid+") has been saved.",position: "bottom"});

	 //reload the json for this movie
	 refreshPosterDetail(pageimdbid);
	// alert("data refreshed for "+imdbid);
	 }
      },
	  error: function(XMLHttpRequest, textStatus, errorThrown){
	  	 		 $.notifyBar({ cssClass: "custom", html: "Error updating'"+savedata.title+"' ("+savedata.imdbid+"). "+errorThrown,position: "bottom"});

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


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

//var detailjson=objectifyForm($('#detailform').serializeArray());
//var selected = $('input[name=radio-choice]:checked', '#mediaflagform').attr('sel');
var myRadio = $('input[name="radio-choice"]');
var checkedValue = myRadio.filter(':checked').attr('sel');
var saveValue= myRadio.filter(':checked').attr('savevalue');
//alert(checkedValue);
var referedby = $("#IMGlistedit").attr('referedby')
$('#'+referedby).attr('src',checkedValue);

$('#'+referedby).attr('savevalue',saveValue);
//alert(+" : "+checkedValue) ;
})

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

//var detailjson=objectifyForm($('#detailform').serializeArray());
//var selected = $('input[name=radio-choice]:checked', '#mediaflagform').attr('sel');


var foo = $('#mediasourcetabs');
//alert(foo.name);
var bar =foo.find('.ui-btn-active');
var selectedsource = bar.attr('tabsource');
var checkedValue="";
if(selectedsource=="mediastore"){
var myRadio = $('input[name="radio-choice-imagestore"]');
checkedValue = myRadio.filter(':checked').attr('sel');
}else if(selectedsource=="url"){
checkedValue=$('#pw').val();
}else if(selectedsource=="web"){
var myRadio = $('input[name="radio-choice-websearch"]');
checkedValue = myRadio.filter(':checked').attr('sel');
}
//alert(checkedValue);


//alert(selectedsource);
var referedby = $("#IMGedit").attr('referedby')

  var edittype= $("#IMGedit").attr('edittype');
//alert(referedby+" - "+edittype);
  if(edittype=="img"){
$('#'+referedby).attr('src',checkedValue);
}else if(edittype=="video"){
$('#'+referedby).attr('src',checkedValue);
$('#'+referedby).parent().load();//attr('src',checkedValue);
//current =$(this).siblings('video').children("source").attr("src");
}
//alert(+" : "+checkedValue) ;
})

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

//var detailjson=objectifyForm($('#detailform').serializeArray());
//var selected = $('input[name=radio-choice]:checked', '#mediaflagform').attr('sel');

var foo = $('#mediasourcetabs');
//alert(foo.name);
var bar =foo.find('.ui-btn-active');
var selectedsource = bar.attr('tabsource');
var checkedValue="";
/*
if(selectedsource=="mediastore"){
var myRadio = $('input[name="radio-choice-imagestore"]');
checkedValue = myRadio.filter(':checked').attr('sel');
}else if(selectedsource=="url"){
checkedValue=$('#pw').val();
}else if(selectedsource=="web"){
var myRadio = $('input[name="radio-choice-websearch"]');
checkedValue = myRadio.filter(':checked').attr('sel');
}*/


//alert(checkedValue);


//alert(selectedsource);
var referedby = $("#IMGedit").attr('referedby')

  var edittype= $("#IMGedit").attr('edittype');
//alert(referedby+" - "+edittype);
  if(edittype=="img"){
$('#'+referedby).attr('src',checkedValue);
}else if(edittype=="video"){
$('#'+referedby).attr('src',checkedValue);
$('#'+referedby).parent().load();//attr('src',checkedValue);
//current =$(this).siblings('video').children("source").attr("src");
}
//alert(+" : "+checkedValue) ;
})

var mylist = $('#j_4');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });


var searchterm = "";
var currentpage = 0;
var totalpages = 1;
var itemsperpage = 20;





$('#mediaflagsearchbutton').bind('click', function(event)
{
//alert($('#j_90search').val());
currentpage=0;
$('#page_index').text("Page "+(currentpage+1)+" of "+totalpages);

refreshMediaFlagList($('#IMGlistedit').attr('editname'), $('#mediaflagsearch').val(),currentpage,itemsperpage);
//refreshPosterList($('#j_90search').val());
})


$('#page_prev').bind('click', function(event)
{
//test();
//alert("prev");
if(currentpage>0){
currentpage = currentpage-1;

$('#page_index').text("Page "+(currentpage+1)+" of "+totalpages);
refreshMediaFlagList($('#IMGlistedit').attr('editname'), $('#mediaflagsearch').val(),currentpage,itemsperpage);

//refreshPosterList($('#j_90search').val(),currentpage,itemsperpage);
}
})


$('#page_next').bind('click', function(event)
{
if(currentpage+1<totalpages){
currentpage = currentpage+1;


//test("foo");
$('#page_index').text("Page "+(currentpage+1)+" of "+totalpages);
refreshMediaFlagList($('#IMGlistedit').attr('editname'), $('#mediaflagsearch').val(),currentpage,itemsperpage);

//refreshPosterList($('#j_90search').val(),currentpage,itemsperpage);
}
})

function refreshMediaFlagList(editname,flagSearchString,flagpage,flagperpage){
	  $('#mediaFlagList').listview().listview('refresh');
$('#mediaFlagList').empty();



$('#mediaFlagList').trigger("create");






	  var jsonurl = "";
	  var counturl = "";
	  if(editname=="Rating"){
	  jsonurl= "ratingslist.json";
	  counturl = "ratingscount.json";
	  }else if(editname=="Resolution"){
	  jsonurl= "resolutionlist.json";
	    counturl = "resolutioncount.json";
	  }else if(editname=="AspectRatio"){
	  jsonurl= "aspectratiolist.json";
	    counturl = "aspectratiocount.json";
	  }else if(editname=="Audio"){
	  jsonurl= "audioformatlist.json";
	    counturl = "audioformatcount.json";
	  }else if(editname=="Studio"){
	  jsonurl= "studiolist.json";
	    counturl = "studiocount.json";
	  }
	  
	  var flagSearchString = $('#mediaflagsearch').val();
	  //var flagpage = 0;
	//  var flagperpage = 20;
	 //alert(flagSearchString);
	 
	 
	    var eventrequest= $.ajax({ 
	  url: counturl+"?Page("+flagSearchString+")", 
	   dataType: "text"});
	  eventrequest.done(function(data){
	  var displayjson=jQuery.parseJSON(data);
	 // alert(displayjson);
	  postercount = displayjson;

	  if(postercount>itemsperpage){
	 // alert("calc pages");
	  totalpages = Math.ceil(postercount / itemsperpage);
	  }else{
	  totalpages=1;
	  }
	  $('#page_index').text("Page "+(currentpage+1)+" of "+totalpages);
$('#mediaflagcount').text(postercount+" Items");
});
	 
	 
	 
	     var eventrequest= $.ajax({ 
	  url: jsonurl+"?page("+flagSearchString+","+currentpage+","+itemsperpage+")", 
	   dataType: "text"});
	  eventrequest.done(function(data){

var displayjson=jQuery.parseJSON(data);
//alert('parsed');
var items = [];
for (let key in displayjson) {
 if (!displayjson.hasOwnProperty(key)) { continue; }
var name =displayjson[key].Name;
var savevalue =displayjson[key].Value;
var imagepath = displayjson[key].ImagePath;
//imagepath=addslashes(imagepath);
 var arg = "<li><label style='align:right; border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;'><fieldset data-role='controlgroup'> ";
arg+="<table width='100%'><tr><td><input type='radio'  name='radio-choice' id='radiochoice_"+name+"' sel='"+imagepath+"' savevalue='"+savevalue+"'> ";  
arg+="<img  class='mediaflaglistimage'  src=\""+imagepath+"\" onerror=\"src='transparent.png'\"/></td><td style='text-align:right;'>"+name+"</td></tr></table></fieldset></label></li>";
 
 
 items.push(arg);
}

$('#mediaFlagList').append( items.join('') ).listview('refresh');

$('#mediaFlagList').trigger("create");
	  });
}
var firstpoll = true;

function pollStatus(){

   setTimeout(function(){
  // this.alert("in function");
   var eventrequest= $.ajax({ 
	  url: "status.json", 
	  /*success: function(data){
		var commandArray = data.split("|");
		for( i=0;i<commandArray.length;i++){
			parseCommand(commandArray[i]);
		}
        //Setup the next poll recursively
        poll();
      },*/
	   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;
 
		//var commandArray = data.split("|");
		//for( i=0;i<commandArray.length;i++){
		//	parseCommand(commandArray[i]);
		//}
        //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){
//alert(com.timestamp+" "+com.message);
//process this command
var messageObj = jQuery.parseJSON(com.message);
//alert(messagseObj.action);
if(messageObj.action=="cached"||messageObj.action=="updated"){
var imdbid= messageObj.imdbid;//com.message.substring(com.message.indexOf(':')+1,com.message.length);
//remove then re-add an li for this imdb
   var eventrequest= $.ajax({ 
	  url: "rawposterdetails.json?id("+imdbid+")", 
	   dataType: "text"});
	  
	  eventrequest.done(function(data){
		var posterobj=jQuery.parseJSON(data);
		
		//alert("load: "+posterobj.title);
		var arg2 =loadPoster(posterobj);
		 //items.push(arg2);
		 $('#'+posterobj.imdbid).remove();
		 $.notifyBar({ cssClass: "custom", html: "'"+messageObj.title+"' has been saved.",position: "bottom"});
		   $('#j_4').append( arg2 ).listview('refresh');
$('#status').text("");
$('#j_4').listview('refresh');
// $('#'+posterobj.imdbid).closest('.rateit').rateit();
 $('#j_4').trigger("create");

 
var mylist = $('#j_4');
var listitems = mylist.children('li').get();

//postercount = listitems.length;
//$('#postercount').text(postercount+" Posters");

//$('.ui-btn-inner, .ui-btn, .ui-btn-up-b, .ui-btn-up-a').css('border:none !important');
var myElements = document.querySelectorAll('.movie .ui-btn-inner');
// alert("found: "+myElements.length);
for (var i = 0; i < myElements.length; i++) {
//    myElements[i].style.borderTop = 0;
}
//sort by whatever was last selected... 
sortDsc("title");
$('.rateit').rateit();
    $(".rateit.rateitedit").bind('rated', function (event, value) { 
	//alert("value: "+value+" ,id: "+$(this).attr('data_imdbid'));
	setRating($(this).attr('data_imdbid'),value);
	});
    $(".rateit.rateitedit").bind('reset', function () { 
	//alert("reset");
	setRating($(this).attr('data_imdbid'),"0"); 
	});
//$('.star').rating();
//$('#j_4').listview('refresh');
 //$('#j_4').trigger("create");

      });


}else if(messageObj.action=="deleted"){


var imdbid= messageObj.imdbid;//com.message.substring(com.message.indexOf(':')+1,com.message.length);
 $('#'+imdbid).remove();

 
 var mylist = $('#j_4');
var listitems = mylist.children('li').get();
postercount = listitems.length;
$('#postercount').text(postercount+" Posters");


		 $.notifyBar({ cssClass: "custom", html: "'"+messageObj.title+"' has been deleted.",position: "bottom"});
	
}else if(messageObj.action=="trailersaved"){


//var imdbid= messageObj.imdbid;//com.message.substring(com.message.indexOf(':')+1,com.message.length);
 //$('#'+imdbid).remove();

 
 //var mylist = $('#j_4');
//var listitems = mylist.children('li').get();
//postercount = listitems.length;
//$('#postercount').text(postercount+" Posters");


		 $.notifyBar({ cssClass: "custom", html: "Trailer for '"+messageObj.title+"' has been saved.",position: "bottom"});
	
}
}

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

}

function loadPoster(posterjson){
// var starRating = "<span class='rateit' id='rateit" + displayjson[key].imdbid + "'  data-rateit-value='" + displayjson[key].userRating + "'  data-rateit-min='0' data-rateit-max='5' data-rateit-ispreset='true' data-rateit-readonly='true'></span>";
    var starRating = "<div class=\"rateit\" id=\"rateit" + posterjson.imdbid + "\"  data-rateit-value=\"" + posterjson.userRating + "\"  data-rateit-min=\"0\" data-rateit-max=\"5\" data-rateit-ispreset=\"true\" data-rateit-readonly=\"true\"></div>";

                           // PosterUtilities.nfo_tools.saveWebThumb(m);
						   
                          var trailer = "transparent.png";
						  var motionposter = "transparent.png";
						  if (posterjson.hasLocalTrailer){
						  trailer = "trailericon.png";
						  }
						  if (posterjson.hasLocalMotionPoster){
						  motionposter = "motionpostericon.png";
						  }
                          var rating = posterjson.userRating;
				var image=		  "transparent.png";
				var originalimage = posterjson.posterThumbnail;
 //image = "/temp/" +  displayjson[key].thumbnail;
                       
                        //    if (m.userRating!=null) { rating = m.userRating.ToString(); }
						                   //      var  arg = "<li class='movie'  id='" + displayjson[key].imdbid + "'  title='" + displayjson[key].title + "'><a class='title' href='#'><img class='lazy' data-original='/temp/" +  displayjson[key].thumbnail + "' src='transparent.png' height='100' /> <h3>" + displayjson[key].title + " </h3><p><img class='lazy' data-original='" + trailer + "' src='transparent.png' height='30' /> <h3>User Rating: " + rating + " " + starRating + " </h3></p></a><a href='#' class='confirm_delete'>Options</a></li>";
                            //var arg = "<li sort-rating = '"+rating+"' sort-rt = '"+posterjson.RTaudienceScore+"' sort-date = '"+posterjson.dateAdded+"' class=\"movie\"  id=\"" + posterjson.imdbid + "\"  title=\"" + posterjson.title +"\"><a class=\"title\" href=\"#\"><img id='image_"+posterjson.imdbid+"' data-original='" +originalimage + "' src='"+originalimage+"' height=\"100px\" /> <h3>" + posterjson.title +" </h3><p>"+ posterjson.mpaaRating+"   RT: "+posterjson.RTaudienceScore+" <div align='right'> <img class=\"lazy\" data-original=\"" + trailer + "\" src=\""+trailer+"\" height=\"30px\" width=\"66px\" /><img class=\"lazy\" data-original=\"" + motionposter + "\" src=\""+motionposter+"\" height=\"30px\" width=\"66px\"/></div> <h3>User Rating: " + rating + " " + starRating + " </h3></p><p>Added on: "+posterjson.dateAdded+"</p></a><a href='#' class='confirm_delete'>Options</a></li>";
var mpaa = "<p></p>";
if(posterjson.mpaaRating.length>0&&posterjson.mpaaRating!=" "&&posterjson.mpaaRating!=""&&posterjson.mpaaRating!="  "){
mpaa = "Rated: "+posterjson.mpaaRating;
}
var rottentomatoes = "<p></p>";
if(posterjson.RTaudienceScore.length>0&&posterjson.RTaudienceScore!=" "&&posterjson.RTaudienceScore!=""&&posterjson.RTaudienceScore!="  "){
rottentomatoes = "Rotten Tomatoes: "+posterjson.RTaudienceScore;

}
							
							var arg2 ="<li sort-rating = '"+rating+"' sort-rt = '"+posterjson.RTaudienceScore+"' sort-date='"+posterjson.dateAdded+"' class=\"movie\"  id=\"" + posterjson.imdbid + "\"  title=\"" + posterjson.title +"\">";
                arg2 +="<a href='#'  style=\"padding: 0px 0px 0px 0px !important;margin: 0px 0px 0px 0px !important;\">";
                  arg2 +=  "<label id=\"checklabel\" style=\"padding: 45px 0px 0px 0px !important;margin: 0px 5px 0px 0px !important;border-width: 0px 1px 0px 0px !important;height:100px;float:left;width:40px;\" data-corners='false'>";
						arg2+="<div class=\"chkdiv\">";
						arg2 +="<fieldset class=\"chk\" id=\"foo\" data-role='controlgroup' style='height:0px !important';border:0px !important>";
             arg2 +=               "<input id='checkbox_"+posterjson.imdbid+"' name='"+posterjson.imdbid+"' class='item_checkbox' type='checkbox' value='false' />";
				arg2 +=		"</fieldset>";	
arg2+="</div>";			
			arg2 +=		"</label>";
			arg2 +=		"<div ><img onclick='ShowPoster(\""+posterjson.imdbid+"\")' src='"+originalimage+"' style='height:145px;float:left;padding-right:10px;'/>";
                 
				  
				  arg2+="<div class=\"infodiv\" position=\"absolute\"><table style=\"border: 0px solid white; overflow:hidden\">"
				   arg2 +=      "<tr class=\"infotablerow\"><td colspan='2'><div class=\"titletext\"><h2 style='padding: 10px 0px 0px 0px'>"+posterjson.title +"</h2></div></td><td></td></tr>";
					arg2 +=	"<tr class=\"infotablerow\"><td colspan='2'>"+mpaa+"</td><td></td></tr>";
					
					arg2+="<tr><td colspan='2'> Rotten Tomatoes: "+posterjson.RTaudienceScore+"</td><td></td></tr>";
					arg2+=" <tr class=\"infotablerow\"><td colspan='2'><div align='left' style='padding: 0px 0px 0px 0px'> <img class=\"lazy\" data-original=\"" + trailer + "\" src=\""+trailer+"\" height=\"30px\" width=\"66px\" />";
					arg2+="<img class=\"lazy\" data-original=\"" + motionposter + "\" src=\""+motionposter+"\" height=\"30px\" width=\"66px\"/></div></td><td></td></tr>";
					
					
					arg2+="<tr class=\"infotablerow\"><td colspan=\"2\">"+starRating+ "</td><td></td></tr>";
					
					arg2+="</table></div>"
					arg2+="<div class=\"dateaddeddiv\" position=\"absolute\" style='padding: 0px 50px 0px 0px;'>Added: "+ posterjson.dateAdded+"</div>";
					arg2+="</div>";
					
					//arg2 +=  "<a href='#posteroptions_1"+posterjson.imdbid+"' data-rel='popup' data-position-to='window' data-inline='true'></a>";
                  arg2 +=  "<a href='#posteroptions_"+posterjson.imdbid+"' data-rel='popup' data-position-to='window' data-inline='true'></a>";
                arg2 +=    "<div data-role='popup' id='posteroptions_"+posterjson.imdbid+"' class='ui-corner-all' style='padding: 10px 10px 10px 10px'>";
				
                     arg2 +=   "<table align='center' data-role='table' id='movie-table' data-mode='reflow' class='ui-responsive table-stroke'>";
                       arg2 += "<thead><tr><th data-priority='1'></th><th data-priority='persist'></th></tr></thead><tbody>";
                      arg2 +=  "<tr><th>Options for '"+posterjson.title+"'</th></tr>";
                        arg2 +="</tbody>";                     
                      arg2 +=  "</table>";                      
                   arg2 +=  "<a onClick = \"DeletePoster(['"+posterjson.imdbid+"'])\"  style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Delete</a>";
                 arg2 +=    "<a onClick = \"CopyPoster('"+posterjson.imdbid+"')\" style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Make a Copy</a>";
                 arg2 +=    "<a style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Refresh Data</a>";
                 arg2 +=    "<a style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Choose Alternate Poster</a>";
                  arg2 +=   "<a onClick = \"ViewDetail('"+posterjson.imdbid+"')\" style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Movie Details</a>";
                 arg2 +=    "<a style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Close</a>";         
		                          // arg2 +=    "<a style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Show on displaygroup0</a>";         

				 arg2 +=   "<div id='manualid'>";
arg2+="<div align='center'>Manual Now Playing</div>";
				arg2+=" <table width='100%'><tr>";
                  arg2 +=   "<td><a onClick = \"StartNowPlaying('"+posterjson.imdbid+"')\" style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Start</a></td>";
				  arg2 +=   "<td><a onClick = \"StopNowPlaying('"+posterjson.imdbid+"')\" style='width:100%' href='#' data-imdb=\""+posterjson.imdbid+"\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b'>Stop</a></td>";
            arg2+= "</tr></table>";
//arg2 += "<tr><td>";
			 arg2 +="<div data-role=\"collapsible\" id = \"content\">  <h2>Show On Display</h2><ul id=\"displays\">";

           // arg2 +="<input type=\"text\" name=\"name2\" id=\"name2\" data-clear-btn=\"true\"><a href=\"#\" >+</a>";
			
        arg2 +="<li><a onClick = \"ShowOnDisplay('"+posterjson.imdbid+"','DisplayGroup0')\"  style='width:100%' data-imdb=\""+posterjson.imdbid+"\" data-displaygroup=\"DisplayGroup0\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b' >DisplayGroup0</a></li>";
		arg2+="<li><a a onClick = \"ShowOnDisplay('"+posterjson.imdbid+"','DisplayGroup1')\"  style='width:100%'data-imdb=\""+posterjson.imdbid+"\" data-displaygroup=\"DisplayGroup1\" data-role='button' data-inline='true' data-rel='back' data-mini='true' data-theme='b' >DisplayGroup1</a></li></ul> </div>";

//arg2 += "</td></tr>";


			
/*			  arg2 +=  "    <a onClick = \"StartNowPlaying('"+posterjson.imdbid+"')\" data-role='button' ";
               arg2 +=  "     data-corners='true' data-iconpos='left' data-inline='false' data-theme='a'>";
              arg2 +=  "      Start Manual 'Now Playing'</a>";
	
                 arg2 +=  "   <a onClick = \"StopNowPlaying('"+posterjson.imdbid+"')\" data-role='button'";
                  arg2 +=  "  data-corners='true' data-iconpos='left' data-inline='false' data-theme='a' >";
                  arg2 +="  Stop Manual 'Now Playing'</a>";

				*/
				arg2+="</div>";
				arg2 +="<div class='mobilebutton4_wrapper '>";
				arg2 +="Set User Rating: ";
arg2 +="<input type='hidden' value='"+posterjson.userRating+"' step='1' id='backing"+posterjson.imdbid+"'>";
arg2 +="<div class='rateit rateitedit' data_imdbid='"+posterjson.imdbid+"' id='rating_"+posterjson.imdbid+"' data-rateit-backingfld='#backing"+posterjson.imdbid+"' data-rateit-resetable='true'  data-rateit-ispreset='true' data-rateit-min='0' data-rateit-max='5'>";
arg2 += "</div>";
arg2 +=  "</div>";
//arg2+="<script>$('#rateit5').rateit();</script>";
               arg2 += "</div>";
                   arg2 += "</a>";
		 arg2 +=  "</li>";
		 return arg2;
}


	function setRating(imdb,rating){
//alert(imdb+" rating wil be set to: "+rating);
//window.open("movielist.html",'_self',false);

    var http = new XMLHttpRequest();

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

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


    http.send(params);

	//update the remote ui starRating
	//var ratingtoupdate = $('#'+imdb).closest('.rateit');
//	alert("updating: "+imdb+" : "+ $("rateit" + imdb).attr('value',rating));
	//var rtu = $("#rateit" + imdb);
	//var oldval = $("#rateit" + imdb).rateit('value');
	//alert("old rating is: "+$("#rateit" + imdb).rateit('value'));
	$("#rateit" + imdb).rateit('value',rating);
		//rtu.rateit();
	//$(ratingtoupdate).bind('rated', function() { alert('rating: ' + $(this).rateit('value')); });  
//ratingtoupdate.attr('value',rating);
}

$(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 () {
  //  $('#editlist').editablelistview();
});
$(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);	
    	}
}
function CopyPoster(imdb)
{
//alert(imdb+" will be Copied. Please reload the cache screen to see changes.");
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="copyPoster("+imdb+")";
    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);
}
function ViewDetail(imdb)
{
alert("show detail "+imdb);
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="getPosterDetail("+imdb+")";
window.open("posterdetail.html?"+command,'_self',false);
}

function StartNowPlaying(imdb)
{
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="startNowPlaying("+imdb+")";
    http.open("POST", "movielist.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);
}
function StopNowPlaying(imdb)
{
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="stopNowPlaying("+imdb+")";
    http.open("POST", "movielist.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);
}

function ShowOnDisplay(imdb,displayid)
{
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="showOnDisplay("+imdb+","+displayid+")";
    http.open("POST", "movielist.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);
}

function GetAlternatePosters(imdb)
{
    var http = new XMLHttpRequest();

    var params = "arg1=Control(Previous)";
var command="getAlternatePosters("+imdb+")";
window.open("alternatePosters.html?"+command,'_self',false);

}


function search(searchString)
{
/*
	//<!--confirm("search "+searchString);-->
	var value = $("input[@name=testGroup]:checked").val();
	//alert(value);
		if(value=="movies"){
		var http = new XMLHttpRequest();	
	var command="search("+searchString+")";
	window.open("searchResult.html?"+command,'_self',false);
	}else if(value=="games"){
		var http = new XMLHttpRequest();	
	var command="search("+searchString+")";
	window.open("gameSearchResult.html?"+command,'_self',false);
	}
	else if(value=="tvshows"){
var http = new XMLHttpRequest();	
	var command="search("+searchString+")";
		window.open("tvsearchResult.html?"+command,'_self',false);
	}
	*/

}

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

function objectifyForm(formArray) {//serialize data function

  var returnArray = {};
  for (var i = 0; i < formArray.length; i++){
    returnArray[formArray[i]['name']] = formArray[i]['value'];
  }
  return returnArray;
}
