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.");
	  }
  }
}


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}, 1000, 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').fadeOut(500);
	$('#join').fadeIn(500);
	$('#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);
 if( player.addModelListener ) {
 addListeners();
 }
}

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


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

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
		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;
	}

// DropDown menu
closetimer = 0;

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

	$("#putincart").click(function(r){
	  var csetid = $("#csetid").val();
	  $.post("/ajax/putincart.php", {"csetid" : csetid}, function(data){
	    alert(data);
	  });
	});
	
	$(".removefromcart").click(function(r){
	  var which=$(this).attr('id').split('_');
	  $.post("/ajax/removefromcart.php", {"csetid" : which[1]}, function(data){
	    if(data!='') {
		  alert(data);
		}
		else {
		  window.location.reload();
		}
	  });
	});
	
  $('.signedsmall').click(function()
  {
    var tmp=$(this).attr('id').split('_');
    $('#signedbig').attr('src','/images/signed-'+tmp[1]+'-big.jpg');
  });
  $('.signedsmall').hover(
    function()
    {
      $(this).css('cursor','pointer');
    },
    function()
    {
      $(this).css('cursor','normal');
    }
  );

  $('.ecpic').click(function()
  {
    var tmp=$(this).attr('id').split('_');
    $('#whichec').attr('src','images/ecards/ecard-eveangel-'+tmp[1]+'.jpg');
    $('#ecardlink').val('ecard-eveangel-'+tmp[1]+'.jpg');
  });
  $('.ecpic').hover(
    function()
    {
      $(this).css('cursor','pointer');
    },
    function()
    {
      $(this).css('cursor','normal');
    }
  );
  
  $('.ecsend').click(function()
  {
    var emtest = new RegExp("^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$");
    if(
      $('#fname').val()!='' &&
      $('#yname').val()!='' &&
      $('#femail').val()!='' &&
      $('#yemail').val()!='' &&
      $('#ecardlink').val()!='' &&
      emtest.test($('#femail').val())==true &&
      emtest.test($('#yemail').val())==true
      )
    {
      $.post
        (
          siteurl+'/ajax/sendmail.php',
          {ajax_action : 'ecard', femail : $('#femail').val(), fname : $('#fname').val(), yemail : $('#yemail').val(), yname : $('#yname').val(), ecard : $('#ecardlink').val(), message : $('#ymessage').val()},
          function(data)
          {
            eval(data);
          }
        );
    }
    else
    {
      alert('All fields are mandatory!');return false;
    }
  });
  $('.spa').click(function(){
    $('#wallpaperdiv').css('display','none');
    $('#ecarddiv').css('display','none');
    $('#signedphotodiv').css('display','block');
  });
  $('.wpa').click(function(){
    $('#wallpaperdiv').css('display','block');
    $('#ecarddiv').css('display','none');
    $('#signedphotodiv').css('display','none');
  });
  $('.eca').click(function(){
    $('#wallpaperdiv').css('display','none');
    $('#ecarddiv').css('display','block');
    $('#signedphotodiv').css('display','none');
  });
	setInterval("slideSwitch()",8000);

	checkVersion();

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

  $('input#search_text').keydown(function(event){
	if(event.keyCode == 13)
	{
		event.preventDefault();
		$('input#search_btn').click();
	}
  });

});
