var infoDivStats = '';
var searchBody = '';

function changeFindView() {
	submitFind();
}

var ascSortValues = Array(
  'title', 'director', 'counry', 'language', 'writer', 'producer', 
  'country', 'genre', 'id', 'filename', 'risk'
  );
function changeFindSort() {
  // switch order based on sort value, all fiels in ascSortValues are best to show asc
  var s = $('#selectSort').val();
  if(ascSortValues.indexOf(s) > -1)
    $('#selectOrder').val('asc');
  else
    $('#selectOrder').val('desc');
  submitFind();
}

function changeFindOrder() {
	submitFind();
}

function changeFind() {
    /*
    if ($('#inputFind').val() && !$('#inputFind').hasClass('placeholder')) {
        submitFind();
    }
    */
}

function changeFindKeyPress(e) {
  keyCode = e.keyCode;
  if(keyCode == 13) {
    submitFind();
  }
}
function urlencode(unencoded) {
  return encodeURIComponent(unencoded).replace(/\'/g, '%27');
}
function queryString(values) {
  q = Array();
  for(var k in values) {
    q[q.length] = urlencode(k) + '=' + urlencode(values[k]);
  }
  return q.join('&');
}

function serializeFind(offset) {
  if(typeof(offset) == 'undefined')
    offset = 0;
  var l = $('#selectList').val();
  if(typeof(l) == 'undefined')
    l = 'all';
  var v = $('#selectView').val();
  if(typeof(v) == 'undefined')
    v = 'poster';
  var s = $('#selectSort').val();
  if(typeof(s) == 'undefined')
    s = 'title';
  var f = $('#selectFind').val();
  if(typeof(f) == 'undefined')
    f = 'all';
  var q = $('#inputFind').val();
  if(typeof(q) == 'undefined')
    q = '';
  if($('#inputFind').hasClass('placeholder')) {
    q = '';
  }
  var a = $('#selectOrder').val();
  if(typeof(a) == 'undefined')
    a = 'asc';

  return queryString({
    'o': offset,
    'l': l,
    'v': v,
    's': s,
    'f': f,
    'q': q,
    'a': a
  });
}

function submitFind(offset) {
    $('.placeholder').val('');
	document.location.href = '/?' + serializeFind(offset);
}

function submitMovieFind() {
    $('.placeholder').val('');
    var q = $('#inputFind').val();
    if ($('#selectFind').val() == 'all')
        document.location.href = '/?o=0&l=all&f=all&q=' + q;
    else if (q != '') {
        movie_query = q;
        highlightSearch();
    }
}

function inputFindKeyPress(e) {
  key = String.fromCharCode(e.charCode ? e.charCode : e.keyCode);
  keyCode = e.keyCode;
  
  if(keyCode == 13) {
    submitMovieFind();
  }
  else {
    var q = $('#inputFind').val() + key;
    var findIn = $('#selectFind').val();
    if(findIn != 'all') {
      if(q.length > 1) {
        movie_query = q;
        highlightSearch();
      }
      else {
        movie_query = '';
        highlightSearch();
      }
    }
  }
}

function clickRegister() {
	document.location.href = "/register";	
}

function clickLogin() {
	document.location.href = "/login";
}

function clickLogout() {
	document.location.href = "/logout";
}

function clickSettings() {
	document.location.href = "/settings";	
}

function clickEnter() {
  document.location.href = "/browse";
}

function clickAbout() {
  document.location.href = "/about";	  
}

function updateInfo(html) {
	$('#infoDiv').html(html);
}

function addList() {
	var l = $('#inputList').val();
	if ($('#inputList').hasClass('placeholder'))
	    l = '';
	if (l == '') {
		var html = '<select id="inputList" class="oxui" style="width: 128px" onChange="changeList()">';
		html += '<option>Select List...</option>';
		for(i = 0; i<userLists.length;i++) {
		  if(userLists[i] && movieLists.indexOf(userLists[i]) < 0)
		    html += '<option value="'+ userLists[i] + '">List: ' + userLists[i] + '</option>';
		}
		html += '<option>New List...</option>';
		html += '</select>';
		$('#listDiv').html(html);
    	oxui.load('#listDiv');
	}
	else if (l == 'Select List...') {
	    clearList()
	}
	else {
		if(typeof(movieId) != 'undefined' && movieId != '') {
			$.getJSON("/json/list/add/" + l + '/' + movieId);
		}
		else {
			$.getJSON("/json/list/add/" + l + '/search?' + serializeFind());
		}
		clearList();
		if (infoDivStats == '') {
  		    infoDivStats = $('#infoDiv').html();
		}
		updateInfo('Added to list ' + l);
		if(userLists.indexOf(l) < 0)
		    userLists[userLists.length] = l;
		if(movieLists.indexOf(l) < 0)
		    movieLists[movieLists.length] = l;
		window.setTimeout("updateInfo(infoDivStats)", 2000);
	}
}

function removeList() {
	var l = $('#inputList').val();
	if ($('#inputList').hasClass('placeholder'))
	    l = '';
	if (l == '') {
		var html = '<select id="inputList" class="oxui" style="width: 128px" onChange="changeList()">';
		html += '<option>Select List...</option>';
		if (typeof(movieId) != 'undefined' && movieId != '') {
  		    for (i = 0; i<movieLists.length; i++) {
  		        if (movieLists[i])
  		            html += '<option value="'+ encodeURI(movieLists[i]) + '">List: ' + movieLists[i] + '</option>';
  		    }
  	    }
  	    else {
  	        for (i = 0; i < userLists.length; i++) {
  		        if (userLists[i] && movieLists.indexOf(userLists[i]) < 0)
  		            html += '<option value="'+ encodeURI(userLists[i]) + '">List: ' + userLists[i] + '</option>';
  		    }
  	    }
	    html += '<option>New List...</option>';
	    html += '</select>';
  	    $('#listDiv').html(html);
    	oxui.load('#listDiv');
    }
	else if (l == 'Select List...') {
	    clearList();
	}
	else {
		if (typeof(movieId) != 'undefined' && movieId != '') {
			$.getJSON("/json/list/remove/" + l + '/' + movieId);
		}
		else {
			$.getJSON("/json/list/remove/" + l + '/search?' + serializeFind());
		}
		clearList();
		if (infoDivStats == '') {
  		    infoDivStats = $('#infoDiv').html();
		}
		updateInfo('Removed from list ' + l);
		if (movieLists.indexOf(l) >= 0)
		    movieLists[movieLists.indexOf(l)] = '';
		window.setTimeout("updateInfo(infoDivStats)", 2000);
	}	
}

function changeList() {
	var l = $('#inputList').val();
	if (l == 'New List...') {
		clearList();
	}
}

function clearList() {
	$('#listDiv').html('<input id="inputList" class="oxui" style="width: 128px" placeholder="List" />');
	oxui.load('#listDiv');
}

function mouseOverItem(id) {
	$('#listItem' + id).css('class', 'centerDiv over');
}

function mouseOutItem(id, className) {
	$('#listItem' + id).css('class', 'centerDiv ' + className);
}

function switchPosters() {
	if (showPosters) {
		showPosters = false;
		$('#headPosters').css('display', 'none');
		$('#headTitleExpanded').hide();
		$('#headTitleCollapsed').show();
		oxui.load('#headTitle');
		if (typeof(headNavigationBar) == 'undefined') {
			$('#head').css('height', '32px');
			$('#movieBody').css('marginTop', '48px');
		}
		else {
			$('#head').css('height', '56px');
			$('#movieBody').css('marginTop', '72px');
		}
		$('#shadowTop').css('top', $('#head').css('height'));
		$('#headBottom').css('top', '4px');
		if($('#browser'))
			$('#browser').css('top', '48px');
		$.getJSON("/json/settings/", {show_posters: 0});
	}
	else {
		showPosters = true;
		$('#headPosters').css('display', 'block');
		$('#headTitleCollapsed').hide();
		$('#headTitleExpanded').show();
		if (typeof(headNavigationBar) == 'undefined') {
			$('#head').css('height', '84px');
			$('#movieBody').css('marginTop', '100px');
		}
		else {
			$('#head').css('height', '108px');
			$('#movieBody').css('marginTop', '124px');
		}
		$('#shadowTop').css('top', $('#head').css('height'));
		$('#headBottom').css('top', '56px');
		if($('#browser'))
			$('#browser').css('top', '100px');
  	    $.getJSON("/json/settings/", {show_posters: 1});
	}
}

function switchInfo() {
    for (var i = 0; i < 3; i++) {
        if ($('#info' + i).css('display') != 'none') {
            $('#info' + i).hide();
            $('#info' + ((i + 1) % 3)).show();
            return;
        }
    }
}

function changeView(view) {
  v = view.value;
  var location = document.location.href;
  if(location.indexOf('?') > 0) {
    location = location.substr(0,location.indexOf('?'));
  }
  location = location + "?v=" + v;
  document.location.href = location;
}

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm) {
  highlightStartTag = '<span class="textHighlight">';
  highlightEndTag = '</span>';

  if(!searchTerm)
    return bodyText;

  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}

function highlightSearchTerms(searchText, treatAsPhrase) {
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }

  if(!searchBody)
    searchBody = $('#main_content').html();
  
  if (!searchBody) {
    return false;
  }
  for (var i = 0; i < searchArray.length; i++) {
    resultBody = doHighlight(searchBody, searchArray[i]);
  }
  
  $('#main_content').html(resultBody);
  return true;
}

function highlightSearch() {
  if (!movie_query){
    if(searchBody) {
      $('#main_content').html(searchBody);
    }
    return;
  }
  highlightSearchTerms(movie_query, true);
}

function trimString(s, length) {
  if(s.length > length) {
    s = s.substr(0, length - 13) + "..." + s.substr(-10);
  }
  return s;
}
