//--------

var Cookie = {
	set:function(name,value,expires,path,domain){
		if(typeof expires=="undefined"){
			expires=new Date(new Date().getTime()+1000*60*60*12);
		}
		document.cookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?"; path="+path:"; path=/")+((domain)?";domain="+domain:"");
	},
	get:function(name){
		var arr=document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
		if(arr!=null){
			return unescape(arr[2]);
		}
		return null;
	},
	clear:function(name,path,domain){
		if(this.get(name)){
		document.cookie=name+"="+((path)?"; path="+path:"; path=/")+((domain)?"; domain="+domain:"")+";expires=Fri, 02-Jan-1970 00:00:00 GMT";
		}
	}
}

//--------

function are_cookies_enabled() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) { 
        document.cookie="testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }
    return (cookieEnabled);
}

//--------

$(document).ready(function () {
	$('.infolist a.register').click(function (e) {
		e.preventDefault();
		$('#reg').modal();
	});
	$('#headertop a.register').click(function (e) {
		e.preventDefault();
		$('#reg').modal();
	});
	$('#headertop a.login').click(function (e) {
		e.preventDefault();
		$('#login').modal2();
	});
});

//-------- activate stylish selects

/*
$(document).ready(function(){
		$('#sel_camtype,#sel_country,#viewmode, #tag2, #info_country,#info_state, #info_city,#sex_chose,#birth_month, #birth_day, #birth_year').sSelect();
});
*/	

//--------

function vote(id,n){
	$.getJSON("?xmode=vote&id="+id+"&num="+n,
		function(data){
			if (data['error']) {
				var html = '<span>' + data['error'] + '</span>';
			} else {
				if (data["numvotes"]==1) {
					var voteword = "vote";
				} else {
					var voteword = "votes";
				}
				var html = '<span>'+ data["rating"] +'</span> from <span>'+ data["numvotes"] + '</span> '+voteword;
			}
			$('.voteinfo').html(html);
			$('.current-rating').attr('style','width:'+data["rating"]*20+'%');
	});	
}

//--------


function login(){
	$('.loginerror').html('');
	var username = $("#lg_username").val();
	var password = $("#lg_password").val();

  $.getJSON("/_process.php?xmode=login&username="+escape(username)+"&password="+escape(password),
		function(r){
			if(r['result']!=''){
				 $('.loginerror').html(r['result']);	
			}
			else{
				Cookie.set( 'mid', r['data']['mid'] );
				Cookie.set( 'xid', r['data']['xid'] );
				Cookie.set( 'uid', r['data']['uid'] );
				Cookie.set( 'through', 'opentopia' );
				window.location.reload();
			}
	});
}

//--------

function logout(){
	//alert('logout. through:'+Cookie.get("through"));
	Cookie.clear("mid");
	Cookie.clear("xid");
	Cookie.clear("uid");
	//alert(Cookie.get("through"));	
	if (Cookie.get("through")=='facebook' || Cookie.get("through")==null || typeof(Cookie.get("through"))==undefined || Cookie.get("through")=='') {
		FB.logout();
	} else {
	}
    window.location.href = "/index.php?logout=1";
}

//--------

function checkname() {
	if ($('#reg_name').val() =='') {
		var html = '<div class="error1">Username can\'t be empty<div>';
		$('.error1').remove();	
		$('.line1').after(html);
		$('#hiname').attr('value','false');
	} else {
		$('.error1').remove();	
		var reg_name=$("#reg_name").val();
	   $.getJSON("/_process.php?xmode=checkusername&username="+escape(reg_name),
			function(data) {
			if (data.length>0){
				$('.error8').remove();	
			 	$(".line1").after(data);
				$('#hiname').attr('value','false');
			} else {
				$('.error8').remove();
				$('#hiname').attr('value','true');
			}				
		});
	}	 
}

//--------

function isEmail(str) { 
	res = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 
	var re = new RegExp(res); 
	return !(str.match(re) == null); 
} 

//--------

function checkemail() {
	$('.error2').remove();
	$('.error5').remove();
	if($('#reg_email').val() =='') {
		var html = '<div class="error2">Email can\'t be empty<div>';
		$('.error2').remove();
		$('.line2').after(html);
		$('#hiemail').attr('value','false');
	} else if(!isEmail($('#reg_email').val())) {
		var html = '<div class="error5">Incorrect email address.<div>';
		$('.error5').remove();
		$('.error2').remove();
		$('.line2').after(html);
		$('#hiemail').attr('value','false');
	} else {
		$('.error2').remove();
	  var reg_email=$("#reg_email").val(); 
	  $.getJSON("/_process.php?xmode=checkemail&email="+escape(reg_email),
			function(data){
			 if (data.length>0){
				 $('.error7').remove();	
				 $('.error5').remove();
				 $(".line2").after(data);
				 $('#hiemail').attr('value','false');
			 }
			 else{
				$('.error7').remove();
				$('#hiemail').attr('value','true');
			}
		});
	}	
}

//--------

function checkpass() {
	if($('#reg_pwd').val().length<6){
		var html = '<div class="error3">Password must have at least 6 characters<div>';
		$('.error3').remove();
		$('.line3').after(html);
		$('#hipass').attr('value','false');
	}
	else{
		$('.error3').remove();
		$('#hipass').attr('value','true');
	}
}

//--------
	
function register(){
	tag = true;
	
	checkname();
	checkemail();
	checkpass();
	$('.error4').remove();
	if($('#hiname').val()=='false'){
		tag = false;	
	}
	if($('#hiemail').val()=='false'){
		tag = false;	
	}
	if($('#hipass').val()=='false'){
		tag = false;	
	}
	if($("#teams").attr("checked")==false){
		tag = false;
		
		var html = '<div class="error4">You must agree to the terms to register.<div>';
		$('.error4').remove();
		$('.line5').after(html);
	}
	
	if (tag == true ) {
		var name_val = $('#reg_name').val();
		var email_val=$("#reg_email").val();
		var pwd_val=$("#reg_pwd").val();
		$.getJSON("/_process.php?xmode=register&username="+escape(name_val)+"&email="+escape(email_val)+"&password="+escape(pwd_val),
			function(data) {
				var html='<p class="registersuccess">Registration Success! We have sent you a verification email. Please click on the URL in the e-mail.';
				$('.success').html(html);			
		});
	}
	
}

//--------

function backlogin(){
	$('#simplemodal-container3 a.modalCloseImg').click();
	$('#login').modal2();
}
function fg_close(){
	$('#simplemodal-container3 a.modalCloseImg').click();
}

function regsuccess_login(){
	$('#simplemodal-container a.modalCloseImg').click();
	$('#login').modal2();
}

//--------

function member(){
	var username = "<?php echo $cur_handle;?>";
	if(username){
		window.location.href="/member.php";
	}else{
		$('#login').modal2();
	}
}

//--------

function add_favorite(id){
	$.getJSON("/_process.php?xmode=favorite&camid="+id,
		function(favorited) {
			if (favorited) {
				$('#favorite').removeClass();
				$('#favorite').addClass('favorited');
				$('#favorite').attr('title',"This is now one of your favorites. Click again to remove it.");
				$('#favorite_label').html("Remove from My Cams");
			} else {
				$('#favorite').removeClass();
				$('#favorite').addClass('notfavorited');
				$('#favorite').attr('title',"This is no longer a favorite. Click again to add it back.");
				$('#favorite_label').html("Add to My Cams");
			}
		}
	);
}

//--------

function submitcomment(){

	var id = $('#camid').val();
	var comments = tinyMCE.getInstanceById('cmt_comments').getBody().innerHTML;
	if (comments=='') {
		alert('Comment can\'t be empty!');
		return;
	}
	else if(comments.length>1500){
		alert('Comment can\'t be more than 1500 characters');
		return;	
	}
	/*$.getJSON("auth/_json.php?funNum=4&id="+id+"&name="+name+"&member_id="+member_id+"&website="+website+"&comments="+comments+"&jsoncallback=?",
		function(data){
			window.location.href="showcam.php?id="+id;
	});*/
	
	$('#addcomment_form').submit();
}

var si = 'close';
function open_close(){
	switch(si){
		case 'close':
			$('.openclose').attr('src','/images/open.gif');
			$('#hottest').attr('style','display:normal');
			si = 'open';
			//Cookie.set('open_close','open');
			break;
		case 'open':
			$('.openclose').attr('src','/images/close.gif');
			$('#hottest').attr('style','display:none');
			si = 'close';
			//Cookie.set('open_close','close');
			break;
	}
}

/* Flipbook Plugin for jQuery
 * Author  :   Jon Raasch
 * Website :   http://jonraasch.com/blog/jquery-flipbook-movies
 * Contact :   jr@jonraasch.com
 * Version :   0.1
 *
 * Copyright (c)2008 Jon Raasch. All rights reserved.
 * Released under FreeBSD License, see readme.txt
 * Do not remove the above copyright notice or text
 *
 *
 * Usage :
 *
 * Place this HTML anywhere on your page: 
 
    <div id="flipbook">
    Loading ...<br />
    <a href="http://jonraasch.com/blog/jquery-flipbook-movies">
    jQuery Flipbook</a>
    </div>

 * 
 * Then include this bit of Javascript to pull images from the directory
 * "images/":
 
     <script type="text/javascript">
     $(function() {
        Flipbook.init( 'images/' ); 
     });
     </script>
 
 *
 */


var Flipbook = {
    obj          : {},
    frameRate    : 8,
    fadeSpeed    : 0,
    ajaxPhp      : 'flipbook.php',
    frames       : $('<div></div>'),
    imageCount   : 0,
    loadedImages : 0,
    isBuilt      : 0,
    loadingAjax  : 0,
    
    init : function( source ) {
        Flipbook.obj.wrapper  = $('#flipbook');
        
        if ( typeof( source ) == 'undefined' ) Flipbook.startFlipping();
        else {
            Flipbook.processSource( source );
            
            Flipbook.isBuilt = 1;
            
            // if the images loaded faster than we were able to set the isBuilt variable, we make sure to start the flipbook here...just a failsafe
            if ( Flipbook.imageCount == Flipbook.loadedImages && !Flipbook.loadingAjax ) Flipbook.startFlipping();
        }
    },
    
    processSource : function( source ) {
        if ( typeof( source ) == 'string' ) source = [ source ];
        for ( var i = 0; i < source.length; i++ ) {
            if ( !Flipbook.isImage( source[i] ) ) Flipbook.addDirectory( source[i] );
        }
    },
    
    isImage : function( source ) {
        var theExt = source.substr( source.length - 4 );
        if ( theExt == '.jpg' || theExt == '.png' || theExt == '.gif' || theExt == '.bmp' ) {
            Flipbook.imageCount++;
       
            // append an image with this source, adding to the loaded images variable once the image is loaded in the browser

            var img = new Image();
            $img = $(img);
            if ( Flipbook.imageCount == 1 ) $img.addClass('active bananas');
            
            $img.load( function() {
                Flipbook.loadedImages++;
                
                // if all images are processed and imageCount == loadedImages and not currently loading any AJAX, start Flipping 
                if ( Flipbook.isBuilt && Flipbook.imageCount == Flipbook.loadedImages && !Flipbook.loadingAjax) Flipbook.startFlipping();
                
            }) . attr('src', source ) . appendTo( Flipbook.frames );
            
            

            return 1;
        }
        else return 0;
    },
    
    addDirectory : function( dir ) {
        Flipbook.loadingAjax++;
        $.ajax({
            type    : 'POST',
            url     : Flipbook.ajaxPhp,
            data    : 'dir=' + dir,
            cache   : false,
            success : function(html) {                
                if ( html ) {
                    Flipbook.loadingAjax--;
                    
                    if ( html != 'empty.dir' ) {
                        var newSource = html.split(',');
                        Flipbook.processSource( newSource );
                    }
                }
            }
        });
    },
    
    startFlipping : function() {        
        // if the flipbook built dynamically, set the flipbook html here, otherwise leave what was on page
        var framesHTML = Flipbook.frames.html();
        if ( framesHTML.length ) Flipbook.obj.wrapper.html( framesHTML );
        
        Flipbook.obj.theFirst = $(':first', Flipbook.obj.wrapper);
        
        $active = $('.active', Flipbook.obj.wrapper);
        if ( !$active.length ) $active = $(':last', Flipbook.obj.wrapper);
        
        Flipbook.obj.active = $active;
        
        Flipbook.play = setInterval( "Flipbook.slideSwitch()", Math.floor( 1000 / Flipbook.frameRate ) );
    },
    
    slideSwitch : function() {
        var $active = Flipbook.obj.active;
    
        var $next =  $active.next().length ? $active.next()
            : Flipbook.obj.theFirst;
    
        if ( Flipbook.fadeSpeed ) {
            $active.addClass('last-active');
            
            $next.css({opacity: 0.0})
                .addClass('active')
                .animate({opacity: 1.0}, Flipbook.fadeSpeed, function() {
                    $active.removeClass('active last-active');
                });
        }
        else {
            $next.addClass('active');
            $active.removeClass('active');
        }
        
        Flipbook.obj.active = $next;
    }

}