$(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); });
  $('#gutschein_lk').click(function () {loadTab(5); });
  //$('#hdcat').click(function () {});

  // 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_first_time(); 			
  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", ".info a", ".infonow1 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",
    clickRemove: true
  });
});

function onBuyMovie(movieID, title, channel, logged) {
  var rqdi=100;
  var flashVersion = getFlashVersion();
  if (flashVersion > 0 && flashVersion < 10) {
    rqdi = 12;
  }
  
  //get the key and start the play of the movie
  $.ajax({
   url:"movie_unique_key.aspx",
   success:function(dataKey) {
    if (!isNaN(dataKey)) {
      $.ajax({url: "dlgrq.aspx?rqdi="+rqdi+"&movieID="+movieID,
        success: function(data) {			    
  		        if (!isNaN(data)) {			       
  					    window.location = "movie_player.aspx?"+"id="+(data*dataKey*3412 + 3);
  					    return;
  				    }
  				    $('#dialog_overlay_').html(data);
  				    openDialog("#dialog_overlay_", 670, 250);
  				    $('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
  				    $('#dialog_close').click(function(){ $.closeDOMWindow(); });
  				    omnilogicPreLogin(title, channel, logged);
  				}
  			});
  		}
  	}  			
  });
}

function onCancelAgbDialog() {
	$.closeDOMWindow();
}

function onContinueToBuy(movieID, title, channel, logged) {
	var chkAgreeTermsCond = 0;
	if ($("#chkAgreeTermsCond").attr("checked")){
		chkAgreeTermsCond = 1;
	}

	var chkAgreeO2UseMyData = 0;
	if ($("#chkAgreeO2UseMyData").attr("checked")){
		chkAgreeO2UseMyData = 1;
	}

  if (chkAgreeTermsCond == 1 && chkAgreeO2UseMyData == 1) {
    if (isValidEmailAddress($("#emailAddress").val())) {
  		$.ajax({
  			url: 'agb.aspx?emailAddress='+$("#emailAddress").val(),
  			success: function(data) {
  				onBuyMovie(movieID, title, channel, logged);
  			}
     	});
     }
     else {
       document.getElementById("invalidEmail").style.display = "block";
       document.getElementById("agreeTermsCond").style.display = "none";
       document.getElementById("agreeO2UseMyData").style.display = "none";
     }	
  } else if (chkAgreeTermsCond == 0) {
       document.getElementById("invalidEmail").style.display = "none";
       document.getElementById("agreeTermsCond").style.display = "block";
       document.getElementById("agreeO2UseMyData").style.display = "none";
  } else {
       document.getElementById("invalidEmail").style.display = "none";
       document.getElementById("agreeTermsCond").style.display = "none";
       document.getElementById("agreeO2UseMyData").style.display = "block";
  }
}

function onNoPermissionToBuy(rqdi) {
  //show general error dialog
	$.ajax({url: "dlgrq.aspx?rqdi="+rqdi,
		success: function(data) {			    
					$('#dialog_overlay_').html(data);
					openDialog("#dialog_overlay_", 670, 250);
					$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
					$('#dialog_close').click(function(){ $.closeDOMWindow(); });
					omnilogicPreLogin(title, channel, logged);
				}
	});
}

function onNoAcceptedAgb(movieID, title, channel, logged) {
    $.ajax({ url: "dlgrq.aspx?rqdi=32"+"&movieid="+movieID+"&title="+title+"&channel="+channel+"&loggedInStatus="+logged,
        success: function(data) {
					$('#dialog_overlay_').html(data);
					openDialog("#dialog_overlay_", 670, 650);
					$('.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 show_profiledlg_first_time (){  
  loadTab(31, 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 = "inpSearch="+$("#inpSearch").attr('value') + "&pageNo=1";	
	$(location).attr("href", "filme_list.aspx?"+params);
}

function removeFromMerkliste(movieID) {
	if(($("#minus"+movieID).attr('class') == "minusButton") ||($("#minus"+movieID).attr('class') == "minusButton minusButtonOver")){
		$.get("deletefrommerkliste.aspx?movieid=" + movieID,"") ;
		$("#minus"+movieID).removeClass();	
		$("#mid"+movieID).remove();
	}
}

/*
function onLicenceTimeClick(movieid, divid) {  
}*/

function ExcludeFromView(contentid) {
    $('#DOMWindow').remove();
  $('#DOMWindowOverlay').remove();
	$.ajax({url: "dlgrq.aspx?rqdi=16",
		success: function(data) {
			$('#dialog_overlay_').html(data);
			openDialog("#dialog_overlay_", 620, 150);
			$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
			$('#dialog_close').click(function(){ $.closeDOMWindow(); });
			$('#dialog_no').click(function()  {$('#DOMWindow').remove(); $('#DOMWindowOverlay').remove(); loadTab(2);} );
			$('#dialog_yes').click(function() {$('#DOMWindow').remove(); $('#DOMWindowOverlay').remove(); $.get("exclude_from_view.aspx?contentid=" + contentid); loadTab(2); } );
		}  	
	});
	fixTooltipIE9();
}

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');
	  });

	  $(".minusButton").parent().mouseout(function() {
		  $(this).attr("title_tt", "Diesen Film von der Merkliste entfernen");
	  });
  }
  else if ($("#"+divid+movieid).hasClass('merkzettelplus') || $("#"+divid+movieid).hasClass('merkzettelminus')) {
	  if ($("#"+divid+movieid).hasClass('merkzettelplus')) {
		  $.get("insertinmerkliste.aspx?movieid=" + movieid,"");
		  $("#"+divid+movieid).removeClass().addClass('merkzettelminus');
		  $(".merkzettelminus").mouseout(function() {
			  $(this).attr("title_tt", "Diesen Film der Merkliste entfernen");
		  });
	  }
	  else {
		  $.get("deletefrommerkliste.aspx?movieid=" + movieid,"");
		  $("#"+divid+movieid).removeClass().addClass('merkzettelplus');
		  $(".merkzettelplus").mouseout(function(){
			  $(this).attr("title_tt", "Diesen Film der Merkliste hinzuf\u00FCgen");
		  });
	  }
  }
  else {
    $.get("deletefrommerkliste.aspx?movieid=" + movieid,"");
    $("#"+divid+movieid).removeClass().addClass('plusButton');
    $(".plusButton").parent().mouseout(function() {
	    $(this).attr("title_tt", "Diesen Film der Merkliste hinzuf\u00FCgen");
    });
    $("#"+divid+movieid).removeClass().addClass('plusButton').mouseover(function() { $(this).removeClass().addClass('plusButton plusButtonOver');
    }).mouseout(function() {
      $(this).removeClass().addClass('plusButton');
    });
  }
}

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'); });
	$('.playMovieButton').mouseover(function() { $(this).removeClass().addClass('playMovieButton playMovieButtonOver');
   	}).mouseout(function() { $(this).removeClass().addClass('playMovieButton'); });	
	$('.deleteButton[active]').mouseover(function() { $(this).removeClass().addClass('deleteButton deleteButtonOver');
   	}).mouseout(function() { $(this).removeClass().addClass('deleteButton'); });   	  
  $('.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'); });
  $('.mailButton').mouseover(function() { $(this).removeClass().addClass('mailButton mailButtonOver');
   	}).mouseout(function() { $(this).removeClass().addClass('mailButton'); });       
  $('.hoursButton24').mouseover(function() { $(this).removeClass().addClass('hoursButton24 hoursButton24Over');
   	}).mouseout(function() { $(this).removeClass().addClass('hoursButton24'); });	
}

function attachTooltip() {	
	$(".minusButton").parent().attr("title_tt", "Diesen Film von der Merkliste entfernen");	
	$(".plusButton").parent().attr("title_tt", "Diesen Film der Merkliste hinzuf\u00FCgen");
	
	bindEasyTooltip({
	classPath: [".movieBoxDetailsButtons a", ".icons a", ".filmTitle a", ".textLine a", ".details_t1_infoLine_col a", ".details_t2_infoLine_col a", "#homeTop10 a", "#btnCoverViewID a", "#btnListViewID 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_) {
	if(cache_!=1){
	  $('#DOMWindow').remove();
	  $('#DOMWindowOverlay').remove();
	}
	fixTooltipIE9();
	
  $.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) {
	$("#hoursButtonOverlay"+movieID).removeClass().addClass('hoursButton24'); //remove the red 24 button
	if(($("#hoursButtonOverlay"+movieID).attr('class') == "hoursButton24") ||($("#hoursButtonOverlay"+movieID).attr('class') == "hoursButton24 hoursButton24Over")){
	
		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:true,				
				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:"Darsteller"},
		{id:3, name:"Regisseur"},
		{id:4, name:"Beschreibung"}
		];
var options_ = [  
		{id:0, name:"Alle"},  
		{id:1, name:"Titel"},  
		{id:2, name:"Darsteller"},
		{id:3, name:"Regisseur"},
		{id:4, name:"Beschreibung"}
		];
function initTopSearchFields() {
 // set default value
  try {	
	   $("#inpSearch").DefaultValue("Suchbegriff 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(description) { openEmptyCategoryDialog(description, 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 OpenTestFilm(){
	$.closeDOMWindow(1, "");
	openTrailerDialog(550,500);
}

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) {  
  	 	    fixTooltipIE9();
		   	
            $('#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(); });
			//on the logout Dialog the close button has to go to the "index" page
			if(dlgID=13) {
				if($('#dialog_close_logout').length>0)
					$('#dialog_close_logout').click(
													function(){
																$.closeDOMWindow();
																window.location= "index.aspx";
													});
				if($('.basic_overlay_close_logout').length>0)
					$('.basic_overlay_close_logout').click(function() {
																		$.closeDOMWindow();
																		window.location="index.aspx";
													});
			}
			
		}  	
	});
}

function openEmptyCategoryDialog(description, dlgID, w, h) {  
	$.ajax({url: "dlgrq.aspx?rqdi="+dlgID,
		success: function(data) {
			$('#dialog_overlay_').html(data);
			$('#emptyDescription').html(description);
			openDialog("#dialog_overlay_", w, h);
			$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
			$('#dialog_close').click(function(){ $.closeDOMWindow(); });
		}  	
	});
}

function openTrailerDialog(w, h) {  
	$.ajax({url: "dlgrq.aspx?rqdi=15",
		success: function(data) {
			$('#dialog_overlay_').html(data);
			openDialog("#dialog_overlay_", w, h);	
			$('.test_trailer_overlay_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());
}

var valuev = null;

/*Crystian*/
function sendBonus(dialog, formf) {
    $('#DOMWindow').remove();
  $('#DOMWindowOverlay').remove();
  
  //check if the user is logged 
  var loginLink = document.getElementById("loginLink");
  if (loginLink) {
    if ($('#loginLink').html().indexOf("Anmelden")>-1) {
        $.get("dlgrq.aspx?rqdi=BONUS_LOGIN&mvieID=-1", function(data) {
      				$('#dialog_overlay_').html(data);
					openDialog("#dialog_overlay_", 670, 250);
      				$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
      				$('#dialog_close').click(function(){ $.closeDOMWindow(); });
					$('#view_content_small').jScrollPane({scrollbarWidth:10, scrollbarMargin:10});
      			});
      		
        return false;
    }
  }
  
  var codev = document.getElementById(((dialog==2)?"code_f1":"code_f"));
  if (valuev) {
	$.get("addVoucher.aspx?code_f="+valuev,"", function(returnv){
		if(returnv=="paket") {
			//voucher used for a packet of movies
			$.get("dlgrq.aspx?rqdi=VOUCHER_OVERLAY1", function(data){
							$('#dialog_overlay_').html(data);
							openDialog("#dialog_overlay_", 670, 250);
							$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
							$('#dialog_close').click(function(){ $.closeDOMWindow(); });   
			});
		} else if(returnv=="format") {
			//voucher used for a specific movie	
			openVoucherOverlay6(valuev);			
		} else if(returnv=="complete") {
			//voucher used for all movies
			openVoucherOverlay4(valuev);			
		} else if(returnv=="bonus") {
			//voucher used for the moment
		
		} else {
			$.get("dlgrq.aspx?rqdi=BONUS_ERROR", function(data) {
							//shows the error message
							$('#dialog_overlay_').html(data);        				
							openDialog("#dialog_overlay_", 670, 450);
							$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
							$('#dialog_close').click(function(){ $.closeDOMWindow(); });        				
							$('#errorMessage').html(returnv);
			});
	}
	
	
    /*$.get("encashBonus.aspx?code_f=" + valuev + "&r=" + Math.random(),"", function(returnv){
	alert("returnv: " +returnv);
      if (returnv == "OK") {
      
          $.get("dlgrq.aspx?rqdi=BONUS_OK", function(data) {			    
        				$('#dialog_overlay_').html(data);        				
        				openDialog("#dialog_overlay_", 670, 250);
        				$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
        				$('#dialog_close').click(function(){ $.closeDOMWindow(); });        				
        		});
                  
      } else {
      
          $.get("dlgrq.aspx?rqdi=BONUS_ERROR", function(data) {			    
        				$('#dialog_overlay_').html(data);        				
        				openDialog("#dialog_overlay_", 670, 250);
        				$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
        				$('#dialog_close').click(function(){ $.closeDOMWindow(); });
        				
        				$('#errorMessage').html(returnv);
 	
        		});      
            			     
			}
		});*/
    });
  }
  return false;
}
function openVoucherOverlay1(){
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	$.get("dlgrq.aspx?rqdi=VOUCHER_OVERLAY1", function(data){
						$('#dialog_overlay_').html(data);        				
        				openDialog("#dialog_overlay_", 670, 250);
        				$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
        				$('#dialog_close').click(function(){ $.closeDOMWindow(); });   
});
}

/*Crina*/
function openVoucherOverlay2() {
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	$.get("get_redeemed_movies.aspx?code_f="+valuev+"&parent="+parent,"", function(data) {			
  			$('#dialog_overlay_').html(data);
  			openDialog("#dialog_overlay_", 670, 470);
  			$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
  			$('#dialog_close').click(function(){ $.closeDOMWindow(); });
			$('.mailButton').bind('click', function() {
														dlgTellAfriend(1, "", this);		
														$("#smallTooltip").remove();
														$(this).removeClass().addClass('mailButton'); 
														});
            $('#view_content_small_overlay2').jScrollPane({scrollbarWidth:10, scrollbarMargin:10});
    });
}

function openVoucherOverlay2WithParam(voucherName, parentOverlay){
	var parent = parentOverlay;
	valuev=voucherName;
	openVoucherOverlay2();
}

function openVoucherOverlay3() {
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	loadTab(5);
}

function openVoucherOverlay4(valuev) {
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	$.get("dlgrq.aspx?rqdi=VOUCHER_OVERLAY4", function(data){
							$('#dialog_overlay_').html(data);        				
							openDialog("#dialog_overlay_", 670, 250);
							$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
							$('#dialog_close').click(function(){ $.closeDOMWindow(); });
    });
}

function openVoucherOverlay_ExpiredMovie() {
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	$.get("dlgrq.aspx?rqdi=VOUCHER_OVERLAY_EXPIRED_MOVIE", function(data){
							$('#dialog_overlay_').html(data);        				
							openDialog("#dialog_overlay_", 670, 250);
							$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
							$('#dialog_close').click(function(){ $.closeDOMWindow(); });
    });
}

function openVoucherOverlay_ExpiredVoucher() {
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	$.get("dlgrq.aspx?rqdi=VOUCHER_OVERLAY_EXPIRED_VOUCHER", function(data){
							$('#dialog_overlay_').html(data);        				
							openDialog("#dialog_overlay_", 670, 250);
							$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
							$('#dialog_close').click(function(){ $.closeDOMWindow(); });
    });
}

function openVoucherOverlay6(valuev) {
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	$.get("voucher_for_specific_movie.aspx?code_f="+valuev,"", function(data) {
			$('#dialog_overlay_').html(data);
			openDialog("#dialog_overlay_", 670, 250);
			$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
			$('#dialog_close').click(function(){ $.closeDOMWindow(); });
			$('#view_content_small').jScrollPane({scrollbarWidth:10, scrollbarMargin:10});
    });
}

function openVoucherOverlayB(movieId){
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	//check what dialog to open
	$.get("existsgutscheine.aspx?movieID="+movieId,"", function(returnv){
		//opens the dialog with the vouchers for the specified movie
		if(returnv=="OK") {
			openOverlayB(movieId);
		}
		//opens a dialog where you can insert a voucher
		if(returnv=="NOK") {
			openBonus();
		}
	});
}

/*Crina*/
function BuyMovieUsingVoucher(voucher, formatId, movieId){
  $('#DOMWindow').remove();
  $('#DOMWindowOverlay').remove();  
  $.get("encashBonus.aspx?code_f=" + voucher +"&fid=" + formatId + "&r=" + Math.random(),"", function(returnv){	
      if (returnv == "OK") { 
	    //get the key
		$.ajax({
				url: "movie_unique_key.aspx",
				success: function(dataKey) {
											window.location = "movie_player.aspx?"+"id="+(movieId*dataKey*3412 + 3);  
										}
				});
	  }
	  else {
          $.get("dlgrq.aspx?rqdi=BONUS_ERROR", function(data) {			    
        				$('#dialog_overlay_').html(data);        				
        				openDialog("#dialog_overlay_", 670, 250);
        				$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
        				$('#dialog_close').click(function(){ $.closeDOMWindow(); });        				
        				$('#errorMessage').html(returnv); 	
        		}); 	     
			}

	});
}

function openOverlayB(movieId){
	$('#DOMWindow').remove();
	$('#DOMWindowOverlay').remove();
	
	$.get("gutscheinemovielist.aspx?movieID="+movieId, function(data) {
  			$('#dialog_overlay_').html(data);
  			openDialog("#dialog_overlay_", 670, 550);
  			$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
  			$('#dialog_close').click(function(){ $.closeDOMWindow(); });
			$('#view_content').jScrollPane({scrollbarWidth:10, scrollbarMargin:10});
    });
}

function openBonus() {
  $('#DOMWindow').remove();
  $('#DOMWindowOverlay').remove();
	
	$.get("dlgrq.aspx?rqdi=BONUS_DIALOG", function(data) {		      	  
  			$('#dialog_overlay_').html(data);        	
  			//$('#DOMWindow').html("");        		
  			openDialog("#dialog_overlay_", 270, 120);          
  			$('.basic_overlay_close').click(function(){ $.closeDOMWindow(); });
  			$('#dialog_close').click(function(){ $.closeDOMWindow(); });        				
  	});
}

//script for showing the ToolTip on Gutschein dialog
function showGutscheinToolTip(offsetY){
	if($(".gutscheine_info").length>0){
		$(".gutscheine_info").each(function() {
			$(this).easyTooltip({
				yOffset:offsetY,
				xOffset:-340,
				useElement:"now_wrapper_"+$(this).attr('id').substring(2)
			});
		}); 
	}
}

function showGutscheinGreyToolTip() {
	if($(".gutscheine_info_grey").length>0){
			$(".gutscheine_info_grey").each(function() {
				$(this).easyTooltip({
					yOffset:80,
					xOffset:-340,
					useElement:"now_wrapper_"+$(this).attr('id').substring(2)
				});
			}); 
		}
}

function showOverlay2ToolTip(){
	if($(".voucherOverlay2ToolTip").length>0) {
		$(".voucherOverlay2ToolTip").each(function() {
			$(this).easyTooltip({
				useElement: "now_wrapper_" + $(this).attr('id').substring(2)	
			});
		});
	}        
}


function openFilmeListeAfterBonus() {
  $('#DOMWindow').remove();
  $('#DOMWindowOverlay').remove();
	
  loadTab(2);  
}

function omnilogic(channelName, pageNo, total){
	//save omnilogic statistics
	var s=s_gi('hasalicealicevod-web');
	if (subChannelName != "") subChannelName = " - " + subChannelName;
	page = "";
	if (pageNo != 0) page = " " + pageNo +"v" + total;
	s.pageName="Alice VOD | " + channelName + subChannelName + page;
	s.prop2=loggedInStatus;
	s.eVar2=loggedInStatus;
	s.channel=channelName + subChannelName;
	flashVersion = FlashDetect.raw;
	s.prop3=flashVersion;
	s.eVar3=flashVersion;
	var s_code=s.t();
	if(s_code)document.write(s_code);
}

function omnilogicDetails(title, channelName, loggedInStatus){
	//save omnilogic statistics
	title.replace("&", "-");
	var s=s_gi('hasalicealicevod-web');
	s.pageName= "Alice VOD | " + title;
	s.prop2=loggedInStatus;
	s.eVar2=loggedInStatus;
	s.channel=channelName;
	flashVersion = FlashDetect.raw;
	s.prop3=flashVersion;
	s.eVar3=flashVersion;
	s.events = "prodView";
	title.replace(";", "-");
	title.replace(",", "-");
	s.products = channelName + ";" + title;
	var s_code=s.t();
	if(s_code)document.write(s_code);
}

function omnilogicSuche(){
	//save omnilogic search statistics
	var s=s_gi('hasalicealicevod-web');
	s.pageName= "Alice VOD | " + channelName;
	s.prop2=loggedInStatus;
	s.eVar2=loggedInStatus;
	s.channel=channelName;
	s.prop3=flashVersion;
	s.eVar3=flashVersion;
	s.eVar4=searched;
	s.eVar5=options[searchIn].name;
	var s_code=s.t();
	if(s_code)document.write(s_code);
}

function omnilogicPreLogin(title, channel, loggedInStatus){
	title.replace("&", "-");
	var s=s_gi('hasalicealicevod-web');
	if (loggedInStatus == "nicht eingeloggt"){
		s.pageName= "Alice VOD | pre_Login";
		s.channel="pre_Login";
		s.events = "event2";
	}
		else{
			s.pageName= "Alice VOD | Leihen";
			s.channel=channel;
			s.events = "scOpen,scAdd";
		}
	s.prop2=loggedInStatus;
	s.eVar2=loggedInStatus;
	flashVersion = FlashDetect.raw;
	s.prop3=flashVersion;
	s.eVar3=flashVersion;
	title.replace(";", "-");
	title.replace(",", "-");
	s.products = channel + ";" + title;
	var s_code=s.t();
	if(s_code)document.write(s_code);
}
function fixTooltipIE9(){
	$("#smallTooltip").remove();
}
