$(document).ready(function () {
  // init for all pages
  initTopSearchFields();		
		
	// user right menu for logged users
	$('#merkliste_lk').click(function () {loadTab(1); });
	$('#ihreFilme_lk').click(function () {loadTab(2); });
	$('#agb_lk').click(function () {loadTab(3); });
	$('#hdcat').click(function () {show_hd_message_dlg();});
	
  // check variables for different states
  if((typeof(userLogoutDoneCAS ) !== 'undefined') && userLogoutDoneCAS) show_logoutCAS_dialog();
  else if((typeof(userLogoutDone ) !== 'undefined') && userLogoutDone) show_logout_dialog();  
  else if(typeof(f_time) !== 'undefined') show_profiledlg(); 			
	else if(typeof(g_ip) !== 'undefined') show_g_ip_dialog(); // set if g_ip failed
	else if(typeof(err_dlg) !== 'undefined') show_err_dialog(err_dlg);  // error messages
  else if(typeof(profile_dlg) !== 'undefined') show_profiledlg();
  
	
  bindEasyTooltip({
    classPath: [".movieBoxDetailsButtons a", ".filmTitle a", ".detailsCol a", ".details_t1_infoLine_col a", "details_t2_infoLine_col a", "#footer .socialLinks a", "#social_lk a" ],
    isContentLinkTitle: true,
    forceContent: true,
    templateName: "template1",
    xOffset: -28,
    yOffset: 53,
    tooltipId: "smallTooltip"
  });
  
});

function onBuyMovie(movieID) {
  var rqdi=100;
  var flashVersion = getFlashVersion();
  if (flashVersion > 0 && flashVersion < 10) {
    rqdi = 12;
  }
  $.ajax({url: "dlgrq.aspx?rqdi="+rqdi+"&movieID="+movieID,
			success: function(data) {			    
			    if(!isNaN(data)) {			       
			       window.location = "movie_player.aspx?"+"id="+data;
			       return;
          }
				$('#dialog_overlay_').html(data);
				openDialog("#dialog_overlay_", 670, 250);
				$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
				$('#dialog_close').click(function(){ $.closeDOMWindow(); });
			}  	
		});
}

function show_profiledlg_rating() {
		$('#DOMWindow').html("");		
		$("#DOMWindow").css("height",620);
		$("#DOMWindow").css("width",620);	
		loadTab(3, hideMerklisteAndFilmlisteTabs);
		$.centerWindow();		             
}

function show_profiledlg (){  
  loadTab(3, hideMerklisteAndFilmlisteTabs);
}

function hideMerklisteAndFilmlisteTabs() {
  var container = jQuery("#basic_overlay_content");
  $(".tab_bar_button_n_sel", container).each(function () {
    this.style.display="none";
  });
  $(".tab_bar_button", container).each(function () {
    this.style.marginLeft="0px";
  });
}


function performSearch() {
	params = "cmbFieldSearch="+$("#FB_cmbFieldSearch_input").attr('hiddenValue') +"&inpSearch="+$("#inpSearch").attr('value') + "&pageNo=1";	
	$(location).attr("href", "filme_list.aspx?"+params);
}

function removeFromMerkliste(movieID) {
	$.get("deletefrommerkliste.aspx?movieid=" + movieID,"")   
	$("#mid"+movieID).remove();
}

/*
function onLicenceTimeClick(movieid, divid) {  
}*/

function AddRemoveMerkliste(movieid, divid) {
  if(movieid == -2) {    
    show_err_dialog(200);
  }
  if(movieid == -1) {     
		$.ajax({url: "dlgrq.aspx?rqdi=6",
			success: function(data) {
				$('#dialog_overlay_').html(data);
				openDialog("#dialog_overlay_", 670, 250);
				$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
				$('#dialog_close').click(function(){ $.closeDOMWindow(); });
			}  	
		});						 
	}		
	
	
if (($("#"+divid+movieid).attr('class') == "plusButton plusButtonOver")||($("#"+divid+movieid).attr('class') == "plusButton")) {
  $.get("insertinmerkliste.aspx?movieid=" + movieid,"");
	$("#"+divid+movieid).removeClass().addClass('minusButton').mouseover(function() { $(this).removeClass().addClass('minusButton minusButtonOver');
   	}).mouseout(function() { 
		$(this).removeClass().addClass('minusButton'); 
		$(this).parent().attr("title", "Diesen Film von der Merkliste entfernen");
	}); 	
	}
else {
  $.get("deletefrommerkliste.aspx?movieid=" + movieid,"");
	$("#"+divid+movieid).removeClass().addClass('plusButton').mouseover(function() { $(this).removeClass().addClass('plusButton plusButtonOver');
   	}).mouseout(function() { 
		$(this).removeClass().addClass('plusButton'); 
		$(this).parent().attr("title", "Diesen Film der Merkliste hinzuf\u00FCgen");
		
	});
	} 
}
function randOrd(){
  return (Math.round(Math.random())-0.5); 
}
 
function insertCloudControl(dataSourceURL) {			
	$.getJSON(dataSourceURL, function(data) {									      
      var boxes = {};
      for (var k=0;k<10;k++) {
        boxes[k] = [];
      }
      //huge
      boxes[0][0] = "B0";
			boxes[0][1] = 7;
			
			boxes[1][0] = "A3";
			boxes[1][1] = 8;			
      //huge
      
      //big
      boxes[2][0] = "B1";
			boxes[2][1] = 7;
			
			boxes[3][0] = "B4";
			boxes[3][1] = 8;
      //big 
			
			//medium
			boxes[4][0] = "A4";
			boxes[4][1] = 9;
			
			boxes[5][0] = "B2";
			boxes[5][1] = 8;
			
			boxes[6][0] = "A1";
			boxes[6][1] = 8;
      
      //small
      boxes[7][0] = "A2";
			boxes[7][1] = 11;			
			
			//samller 
      boxes[8][0] = "A0";
			boxes[8][1] = 10;
			
			boxes[9][0] = "B3";
			boxes[9][1] = 7;
									
			$.each(data.tags, function(i, val) {
			
       if(i < 10){
        var box = $("#" + boxes[i][0]);
        var txt = val.tag; 
        if(String(val.tag).length  > boxes[i][1]){
          txt = String(val.tag).substring(0,boxes[i][1]);
        } 
       
        $("<a>").text(txt).attr({href:"filme_list.aspx?catID=" + val.id}).appendTo(box);  
        
       } 			
			});
		});
}



function attachOver() {
	$('.playButton').mouseover(function() { $(this).removeClass().addClass('playButton playButtonOver');
   	}).mouseout(function() { $(this).removeClass().addClass('playButton'); });
  $('.mailButton').mouseover(function() { $(this).removeClass().addClass('mailButton mailButtonOver');
   	}).mouseout(function() { $(this).removeClass().addClass('mailButton'); });     
  $('.plusButton').mouseover(function() { $(this).removeClass().addClass('plusButton plusButtonOver');
   	}).mouseout(function() { $(this).removeClass().addClass('plusButton'); });
  $('.minusButton').mouseover(function() { $(this).removeClass().addClass('minusButton minusButtonOver');
   	}).mouseout(function() { $(this).removeClass().addClass('minusButton'); });        	
}

function attachAddThis() {
	var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
	if (window.addthis){ window.addthis = null; }
	$.getScript( script );
}

function attachTooltip() {	
	$(".minusButton").parent().attr("title", "Diesen Film von der Merkliste entfernen");	
	$(".plusButton").parent().attr("title", "Diesen Film der Merkliste hinzuf\u00FCgen");
	
	$(".hoursButton24").parent().attr("title", "Die Lizenzdauer betr\u00E4gt 24 Stunden");	
	$(".hoursButton").parent().attr("title", "Die Lizenzdauer betr\u00E4gt 48 Stunden");
	
	bindEasyTooltip({
    classPath: [".movieBoxDetailsButtons a", ".filmTitle a", ".textLine a", ".details_t1_infoLine_col a", ".details_t2_infoLine_col a", "#homeTop10 a"],
    isContentLinkTitle: true,
    forceContent: true,
    templateName: "template1",
    xOffset: -28,
    yOffset: 53,
    tooltipId: "smallTooltip"
  });
	
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function ReportingCallback(p1, p2, p3, p4, p5) {
    if (typeof(reportingID)!="undefined") {
        if (reportingID>0) {
            if (p1=="playTime") {
                query = "s=reporting&repID=" + reportingID + "&play=" + firstPlay + "" + "&r=" + Math.random();
                jQuery.get("reporting.aspx",query);
                firstPlay = 1;                     
            }                     
        }
    }
}

function keepalive_fct(){
    var upUrl = "keepalive.aspx?r=" + (new Date().getMilliseconds( )) + Math.random();
    $.get(upUrl);
}


function openDialog(name_, width_, height_, cache_) {
  $.openDOMWindow({ 
        loader:1, 
	height: height_, 
	width: width_, 
        loaderImagePath:'animationProcessing.gif', 
        loaderHeight:16, 
        loaderWidth:17, 
        windowSourceID:name_,
        cache:cache_
        
  });
} 

function onBuyMovie_close() {
    account_bind_actions();
}

function onBuyMovie_logged(movieID) {
    cache_b = $('#DOMWindow').html();
    callback_cache = onBuyMovie_close;	
    pp = $("#DOMWindow").css("top");
    $.ajax({
  		url: "dlgrq.aspx?rqdi=100&movieID="+movieID,
  	 	   success: function(data) {
    	 	   if(!isNaN(data)) {			       
  			       window.location = "movie_player.aspx?"+"id="+data;
  			       return;
            }        
            $('#DOMWindow').html(data);
			       openDialog("#DOMWindow", 625, 470, 1, onBuyMovie_close);              	 	     	 	      					 			    
            $("#DOMWindow").css("top", pp);            
            $('.basic_overlay_close, #dialog_close, #abrechen').click(function() { 
                $.closeDOMWindow(1, onBuyMovie_close);                 
            });            
        }									
			});															
}

function dlgTellAfriend(level, cb, ob) {		
	if(level == 0) {
		cacheContent = 0;
		divName = "dialog_overlay_";	
	} else {
		divName = "DOMWindow";
		cacheContent = 1;		
		
	}	
	var pp=0;
	if(level == 1)
		pp = $("#DOMWindow").css("top");		
	
  	$.ajax({
		url: 'dlgrq.aspx?rqdi=4',
		success: function(data) {
			if(cacheContent == 1) {
				cache_b = $('#'+divName).html();
				callback_cache = cb;
			}						
			
			$('#'+divName).html(data);
			openDialog("#"+divName, 625, 470, cacheContent, cb);					 
			if(level == 1)
				$("#DOMWindow").css("top", pp);		  
			  $('#dialog_send').click(function() {
				$("#movieID").attr('value', ob.id);
				
				$("#frmTellAFriend").ajaxForm(function() {                  					
					   // result dialog
             $.ajax({url: "dlgrq.aspx?rqdi=11",
			       success: function(data) {
                	$("#DOMWindow").html(data);		             

  				        $('.basic_overlay_close').click(function() {                
                    if(cacheContent == 1) {   
                      // $.closeDOMWindow(cacheContent, cb);                  
                      $("#DOMWindow").html(cache_b);
                      account_bind_actions();                  
                    } 
                    else
                      $.closeDOMWindow();                    
                  });				        				        
			         }  	
		        }); 					   
				});
				if($("#frmTellAFriend").validate().form()) {
					$("#frmTellAFriend").submit();						 
				}
			});											
			$('.basic_overlay_close, #dialog_close, #abrechen').click(function(){ $.closeDOMWindow(cacheContent, cb); });			
			valitateTellFriend();		
		}
	});		
} 


function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function validateTellFriend_() {
	alert($('from').value());	
	
}

function checkToFields() {
	if(
	(($('#name1').val().length < 2) && ($('#email1').val().length == 0)) &&	
	(($('#name2').val().length < 2) && ($('#email2').val().length == 0)) &&
	(($('#name3').val().length < 2) && ($('#email3').val().length == 0)) &&
	(($('#name4').val().length < 2) && ($('#email4').val().length == 0)))
		return true;
	return false;
}


function valitateTellFriend() {	
	$("#frmTellAFriend").validate({			
		rules: {
			from: {
				required: true,
				minlength: 2
			},
			email_from: {
				required:true,
				email: true
			},
			
			name1: { required:function(element)  { 
				if(checkToFields())
					return true;
					
				return ($('#email1').val().length != 0); }, minlength:2 
			},
			name2: { required:function(element) { return ($('#email2').val().length != 0); }, minlength:2 },
			name3: { required:function(element) { return ($('#email3').val().length != 0); }, minlength:2 },
			name4: { required:function(element) { return ($('#email4').val().length != 0); }, minlength:2 },
			
			email1: { required:function(element) {			
				return ($('#name1').val().length != 0); }, 
				
				email: true 
			},
			email2: { required:function(element) { return ($('#name2').val().length != 0); }, email: true },
			email3: { required:function(element) { return ($('#name3').val().length != 0); }, email: true },
			email4: { required:function(element) { return ($('#name4').val().length != 0); }, email: true }
			
		},
		messages: {
			from: {
				required:"",
				minlength:""
			},
			email_from: {
				required:"",
				email:""
			},
			name1:  { required:"", minlength:"" },
			name2:  { required:"", minlength:"" },
			name3:  { required:"", minlength:"" },
			name4:  { required:"", minlength:"" },			
			email1: { required:"", email:"" },
			email2: { required:"", email:"" },
			email3: { required:"", email:"" },
			email4: { required:"", email:"" }
		}		
	});
}

setInterval(keepalive_fct, 60000*10);

function bindEasyTooltip(config) {
  
  if (config.classPath.length > 0) {
    for (var k=0;k<config.classPath.length;k++) {
      var classPath = config.classPath[k];
      $(classPath).each(function () {
        var content = config.content;
        if (config.isContentLinkTitle === true) {
          content = $(this).attr("title");
        }
        try {
          var browserName=navigator.appName; 
          var browserVer=parseInt(navigator.appVersion); 
          var templateName = config.templateName;
          browserVer = parseFloat(navigator.appVersion.split("MSIE")[1]);
          if (browserName=="Microsoft Internet Explorer" && browserVer < 7) {
            templateName = "template1_ie6";
          }
        } catch (e) {
        }
    	  $(this).easyTooltip({
    	     forceContent: config.forceContent,
    	     content: content,
           template: templateName,
           xOffset: config.xOffset,		
    			 yOffset: config.yOffset,
           tooltipId: config.tooltipId 
         });
      });
    }
  }
}   

function getFlashVersion() {
  return getFlashVersionString().split(',').shift();
}

function getFlashVersionString(){ 
  // ie 
  try { 
    try { 
      // avoid fp6 minor version lookup issues 
      // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ 
      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
      try { axo.AllowScriptAccess = 'always'; } 
      catch(e) { return '6,0,0'; } 
    } catch(e) {} 
    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
  // other browsers 
  } catch(e) { 
    try { 
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
      } 
    } catch(e) {} 
  } 
  return '0,0,0'; 
} 



// --------------------------------------------------------------------------------------------------------------------
// initialise all top search combo box and attach events for input and button
var options = [  
		{id:0, name:"Alle"},  
		{id:1, name:"Titel"},  
		{id:2, name:"Schauspieler"},
		{id:3, name:"Regisseur"},
		{id:4, name:"Beschreibung"}
		];
var options_ = [  
		{id:0, name:"Alle"},  
		{id:1, name:"Titel"},  
		{id:2, name:"Schauspieler"},
		{id:3, name:"Regisseur"},
		{id:4, name:"Beschreibung"}
		];
function initTopSearchFields() {
   // init combobox
 
   
   $.extend({
		cmbFieldSearchOptions: options
	 });	

	var FB = $('#FB_cmbFieldSearch').flexbox(
		{ results: $.cmbFieldSearchOptions },
		{
		  arrowClickAdditionalFunction: arrowClickAdditionalFunction,
			width: 128,
			allowInput: false,   			
			onSelect: function() {
			}
		}
	);
  
	$('#FB_cmbFieldSearch').setValue($.cmbFieldSearchOptions[0].name);
	
	/*$('#FB_cmbFieldSearch_arrow').click(function(){
		$('#FB_cmbFieldSearch_input').val('');
	});*/
 
	function arrowClickAdditionalFunction() { 
      $('#FB_cmbFieldSearch_input').val('');
  }
 
 // set default value
  try {	
	   $("#inpSearch").DefaultValue("Hier Suchwort eingeben...");
	} catch (e) {}
	
	// atach event for Enter on input and searchButton click
	$("#btnSearch").click(function() { performSearch(); } ); // attach click
	$('#inpSearch').keypress(function(e) { if(e.which == 13) { performSearch(); }});     
}

// dialog functions
function show_g_ip_dialog() { if(g_ip==1) { openSimpleDialog(5, 620, 150); } }
function show_err_dialog(err_dlg_) { if(err_dlg_ == 200 || err_dlg_ == 201 || err_dlg_ == 300 || err_dlg_ == 400) {	openSimpleDialog(err_dlg_, 620, 150);} }
function show_hd_message_dlg() { openSimpleDialog(7, 620, 150); }
function show_ng_flash_dialog() { openSimpleDialog(10, 620, 150); }
function show_ftuser_dialog() { show_profiledlg(); }
function show_logout_dialog() { openSimpleDialog(13, 620, 150); }
function show_logoutCAS_dialog() { openSimpleDialog(14, 620, 150); }

function show_rating_check_dialog(sr) {    
		$.ajax({url: "dlgrq.aspx?rqdi=9",
			success: function(data) {		        
				$('#dialog_overlay_').html(data);
				openDialog("#dialog_overlay_", 620, 150);
				$('.basic_overlay_close').click(function(){ repaintOldRat(sr); $.closeDOMWindow(); });
				$('#dialog_close').click(function(){repaintOldRat(sr); $.closeDOMWindow(); });
				$('#profil_dialog').click(function(){  repaintOldRat(sr); show_profiledlg_rating();});
			}  	
		});
}

function show_ng_flash_dialog_logged() {
    cache_b = $('#DOMWindow').html();
    callback_cache = onBuyMovie_close;	
    pp = $("#DOMWindow").css("top");
    $.ajax({
  		url: "dlgrq.aspx?rqdi=10",
  	 	   success: function(data) {    	 	   
            $('#DOMWindow').html(data);
			       openDialog("#DOMWindow", 625, 470, 1, onBuyMovie_close);              	 	     	 	      					 			    
            $("#DOMWindow").css("top", pp);            
            $('.basic_overlay_close, #dialog_close, #abrechen').click(function() { 
                $.closeDOMWindow(1, onBuyMovie_close);                 
            });            
        }									
			});
}

function openSimpleDialog(dlgID, w, h) {  
	$.ajax({url: "dlgrq.aspx?rqdi="+dlgID,
		success: function(data) {
			$('#dialog_overlay_').html(data);
			openDialog("#dialog_overlay_", w, h);
			$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
			$('#dialog_close').click(function(){ $.closeDOMWindow(); });
		}  	
	});
}


function getFlashMovieObject(movieName) {
  if (window.document[movieName])  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1) {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
  return null;
}

function isPlaying(){
	var flashMovie=getFlashMovieObject("myPlayer");
	if(flashMovie != null)
		alert(flashMovie.isPlaying());
}