function getInternetExplorerVersion()
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function checkVersion()
{
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver < 7.0 )
	  {
	      alert("You should upgrade your copy of Internet Explorer.");
	  }
  }
}

function autoCompleteModelSearch(e){
  if( e.length >= 2 ) {
		$.post('/ajax/inlineModelSearch.php',{'in': e},function(data){
			if(data!='') {
				showModelSuggestions(data);
        //alert(data);
			}
		});
	} else {
		hideModelSuggestions();	
	}
}
function showModelSuggestions(d) {
	$('.modelSuggestionsHolder').fadeIn(100);
	$('.modelSuggestionsHolder').html(d);	
}

function hideModelSuggestions() {
	$('.modelSuggestionsHolder').fadeOut(100);
	$('.modelSuggestionsHolder').html('');			
}

var player = null;

function slideSwitch() {
   var $active = $('.slideshow img.active');
    if ( $active.length == 0 ) $active = $('.slideshow img:last');
    var $next =  $active.next().length ? $active.next() : $('.slideshow img:first');
    $active.addClass('last-active');
    $next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 2000, function() {
            $active.removeClass('active last-active');
     });
}

function videoView() {
  var set_id = $('#set_id').html();
  $.post(siteurl+'/ajax/viewVideo.php',{'id': set_id});
}

function displayJoin() {
     $("#player").css('display','none');
	 $('div.video-preview').css('height','340px');
	 $("#join").fadeIn(250);
	 $("#player_wrapper").css('display','none');
}

function addListeners()
{
 if (player) { 
  player.addModelListener("STATE", "stateListener");
 } else {
  setTimeout("addListeners()",100);
 }
}

function playerReady(thePlayer)
{
 player =  document.getElementById(thePlayer.id);
 addListeners();
}

function stateListener(obj) 
{ //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
    currentState = obj.newstate; 
    previousState = obj.oldstate; 
   	if ( currentState == "COMPLETED" && (previousState == "IDLE" || previouseState == 'PLAYING') )
    {
	  displayJoin();
	} else if( previousState == 'IDLE' && currentState == 'BUFFERING' ) {
	  videoView();
	}
}




function isImgLoaded(img){	
	if(!img.attr('complete')){
		//for IE
		//alert(img.attr('src')+'IE false, complete: '+img.attr('complete'));
		return false;
	}	
	if( img.attr('complete') != 'undefiend' && (img.attr('naturalWidth') == 0 || img.attr('width') == 0 || img.attr('width') < 50) ){
		//for FF
		
		//fuckin hacking for Opera...
		//	Opera reports complete=undefined, naturalWidth=undefined, width = some kind of sum of the width of parent elements, so it's no fuckin 0
		//	so use 50px, as all photos should be bigger than that (hope so...)
		
		//alert(img.attr('src')+', complete: '+img.attr('complete')+', natwidth: '+img.attr('naturalWidth'));
		return false;
	}	
	return true;	
}

function CheckForm(f) {
	var email_re = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
	if (!email_re.test(f.email.value)) {
		alert("Please enter your email address.");
		f.email.focus();
		return false;
	}

		return true;
	}

function showSubmenu(e) {
	cancelTimeout();
	jQuery(e).css('display','block');
}

function hideSubmenu(e) {
	jQuery(e).css('display','none');
}

function closeTimeout(e) {
	closetimer=setTimeout('hideSubmenu(\''+e+'\')',500);
}

function cancelTimeout() {
	if(closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

function repositionFixed() {
  
  // repositions fixed elements on the page
  // used for ipad / ipod / iphone
  
  joinbutn = document.getElementById('join-button-left');
  langob = document.getElementById('languages');
  qrcode = document.getElementById('qrcode');

  var wheight = $(window).height();

  if(joinbutn) joinbutn.style.position = 'absolute';
  if(langob) langob.style.position = 'absolute';
  if(qrcode) qrcode.style.position = 'absolute';
  
  if( orientation == 90 || orientation == -90 ) {
    if(joinbutn) joinbutn.style.top = (window.pageYOffset + (wheight/2 - 100)) + 'px';
    if(langob) langob.style.top = (window.pageYOffset + 35) + 'px';
    if(qrcode) qrcode.style.top = (window.pageYOffset + wheight / 2 ) + 180 + 'px';      
  } else {
    if(joinbutn) joinbutn.style.top = (window.pageYOffset + (wheight/2 - 120)) + 'px';
    if(langob) langob.style.top = (window.pageYOffset + 35) + 'px';
    if(qrcode) qrcode.style.top = (window.pageYOffset + wheight * 0.9 ) + 5 + 'px';
  }
}

if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
  window.onscroll = repositionFixed;
  window.onorientationchange = repositionFixed;
};

// DOM Ready

$(document).ready(function(){
    $("#email_submit").click(function(r){
       var email = $("#sing_up_nl").val();
       var code = $("#safe_code").val();
       
       var email_valid = validate(email);
       if(email_valid){
            $.post("ajax/checkCode.php",{"code" : code},function(data){
                if(data == "1"){
                    $.post("ajax/subScribe.php",{"email" : email},function(data){
                        if(data == "1"){
                            alert("Succesfull signup.");
                        }
                    });
                } else {
                    alert("Try again later.");
                }
            });
       } else {
            alert("Invalid Email Address");
       } 
    });
    

	$('a.preview').fancybox({
		'hideOnContentClick'	: true,
		'hideOnOverlayClick'	: true,
		'centerOnScroll'		: true,
		'overlayShow'			: false
	});
	
	$('div.features').fadeIn(1000);
    $('div.features ul li').fadeIn(1000); // tweak for IE

	
	$('.fancybox a').click(function(){
		fancybox_url = $(this).find('span.fancybox_modelpic_url');
		if(fancybox_url && fancybox_url.html()){
			img_url = fancybox_url.html();
		} else {
			img_url =  $(this).find('img').attr('src');
		}
		
		obj = $.fancybox({
			'href'	:	img_url,
			'title'	:	$(this).attr('title')
		});
		
		return false;
	});
	

   $("#ddfcarousel").jcarousel({
   	wrap: "last",
   	visible: 5
   });	


	$('input.models').click(function(){
		var act = "remove";
		var result = $('div#search_result');
		result.html("Searching ...");
		var search = new Array();
		$('input:checked').each(function(i){
		 var e = $(this);
		 var id = e.attr('id').split("-",2);
		 id = id[1];
		 search[i] = id;
		});
		$.post('/ajax/tourModelSearchByKeyword.php',{ kwid: search },function(data){
		 if(data!='')
		 {
			result.html(data);
		 }
		});
	});

	$('input.scenes').click(function(){
		var act = "remove";
		var result = $('div#search_result');
		result.html("Searching ...");
		var search = new Array();
		$('input:checked').each(function(i){
		 var e = $(this);
		 var id = e.attr('id').split("-",2);
		 id = id[1];
		 search[i] = id;
		});
		$.post('/ajax/tourSetSearchByKeyword.php',{ kwid: search },function(data){
		 if(data!='')
		 {
			result.html(data);
		 }
		});
	});

	$('input#search_btn').click(function(){
		var result = $('div#search_result');
		var txt = escape($('input#search_text').val());
		result.html("Searching ...");
		$.post('/ajax/tourSetSearchByText.php',{ text: txt },function(data){
			if(data!='')
			{
				result.html(data);
			}
		});
	});

	$('#uname').focus(function(){if($(this).val()==$(this).attr('rel')){$(this).val('');}});
	$('#uname').blur(function(){if($(this).val()==''){$(this).val($(this).attr('rel'));}});
	$('#pswd').focus(function(){if($(this).val()==$(this).attr('rel')){$(this).val('');}});

	setInterval("slideSwitch()",5000);

	checkVersion();

  $('#modelname').keyup(function()
  {
    autoCompleteModelSearch($(this).val());
  });

});
