var topspan=0;
var tabtwo=0;
$(document).ready(function() {
   
	$('#tabs-portfolio').tabs({ 
		selected: 0 ,
		show: function(event, ui) { 
			if(ui.index == 1 && tabtwo == 0) {
				 $("#home_logos").easySlider({
			                auto: false,
			                continuous: false,
			                prevText: '',
			                nextText: '',
				            prevId: 'logoprevBtn',
			                nextId: 'logonextBtn',
			                speed: 300,
			                pause: 8000
			     });
				tabtwo=1;
			}
		}
	}); //menu/pages tabs
	fancy();
	$.pop();
	initCastomForms();
	initCustomFile();
	$(".step-prev").click(function(){
		history.go(-1);
	});
	
	if($("#contentFlow").length >= 1) {    
	
    var cf = new ContentFlow('contentFlow', {
    	reflectionColor: "#000000",
    	scaleFactor: 1.5,
    	onclickActiveItem : function() {
    		return;
    	}
    	});
    }


     $("#content a").each(function(e){
//			console.log($(this).attr('href'));
		if($(this).attr('href').match(/(jpeg|png|gif|image\.php|files)/i)) {
			var org = $(this).attr('href')
			$(this).attr('href',org+"&.jpg")

		     $(this).fancybox({                                                                                                                                        
                'type'			: 'image',
                'zoomSpeedIn'   : 0,                                                                                                                              
                'zoomSpeedOut'  : 0,                                                                                                                              
                'overlayShow'   : true,                                                                                                                           
                'padding'       : 2,
                'overlayOpacity': 0.8,
                'overlayColor'  : "#000",
                'scrolling'		:  true,
                'centerOnScroll' : false,
                'autoScale'		: false
		     });

		}
     });


 $("#home_images").easySlider({
                auto: false,
                continuous: false,
                prevText: '',
                prevId: 'imageprevBtn',
                nextId: 'imagenextBtn',
                nextText: '',
                speed: 300,
                pause: 8000
     });




              
	
	if($(".secure").length >= 1) {                                                                                                                                              
        $.get(base+"token.php",function(txt){                                                                                                                                      
                $(".secure").append('<input type="hidden" name="ts" value="'+txt+'" />');                                                                                           
        });                                                                                                                                                                         
    }      

	$(".step-next").click(function(){
		
		if( $("#login-form").length == 1 && $("#login-form").valid() ) {
			$("#login-form").submit();
		}
		
		if( $("#card-form").length == 1 && $("#card-form").valid() ) {
		
			block();

			$("#card-form").submit();
		}
	});
	
	
	$(".send").click(function(){
		if( $("#payform").length == 1 && $("#payform").valid() ) {
			$("#payform").submit();
		}

	});



	$(".send-form").click(function(){

		if( $("#samples-form").length == 1 && $("#samples-form").valid() ) {
			$("#samples-form").submit();
		}

		if( $("#order-form").length == 1 && $("#order-form").valid() ) {
			$("#order-form").submit();
		}


	});

	
	 $("#samples-form").validate() 
	// same shiping
	
	$("#same").click(function(){
		if($(this).is(":checked")) {
			$("#shipping_address").slideUp();
		} else {
			$("#shipping_address").slideDown();
		}
	})

	// paypal 
	$("#paypalsubmit").click(function(){
		$("#paypal_form").submit();
	});
	
	if($("#paypal_form").length == 1) {
		$("#paypal_form").submit();
	}
	// hero panels	
	
	$("#hero").tabs({selected: stab});	
	$(".type1").mouseover(function(){
		$("#hero").tabs('option', 'selected', 0);
	});

	$(".type2").mouseover(function(){
		$("#hero").tabs('option', 'selected', 1);
	});

	$(".type3").mouseover(function(){
		$("#hero").tabs('option', 'selected', 2);
	});



	$("#addfiles").click(function(){
		$("#morefile").slideDown();
		$(".add").hide();
	});
	
	$("#card-form").validate({
            ignore: ':not(:visible)'
     });

	$(".optionsUL li a").click(function(){
//		checkPrice();
	});

	
	$("#login-form").validate({
/*
                invalidHandler: function(form, validator) {
                      var errors = validator.numberOfInvalids();
                      if (errors) {
                        var message = errors == 1
                          ? 'You missed <em class="error">1 field</em>. It has been highlighted'
                          : 'You missed <em class="error">' + errors + '</em> fields. They have been highlighted';
                        alert(message,function(){
                                        //$("#applyjobForm").submit();
                                });

                      } else {
                        $("div.error").hide();
                      }
                    },
*/
            ignore: ':not(:visible)',
            rules : {
            	username: {minlength: 5},
            	username1: {minlength: 5},
            	password2: {equalTo: "#password1"},
            	email: {
            				remote: "/cards?shop=verify"
            				
            			},
            	email2: {equalTo: "#email"},
            	postcode: {number: true}
            },
            messages: {
            	email: {
	            	required: " ",
	            	email: "Please enter a valid email address",
            		remote: jQuery.validator.format("This email address is taken.")
            	}
            }
        });

	

	 $(".fancytxt").fancybox({                                                                                                                                        
                        'zoomSpeedIn'	: 0,                                                                                                                                 
                        'zoomSpeedOut'	: 0,                                                                                                                                 
                        'overlayShow'	: true,                                                                                                                              
                        'padding'       : 5,
                        'overlayOpacity': 0.8,
                        'overlayColor'  : "#000",
                        'frameWidth'	: 920,
                        'frameHeight'	: 600,
                        'callbackOnShow': coll,
                        'hideOnContentClick': false,
                        'hideOnOverlayClick': false
     });



	$(".registerlogin").change(function(){
		
		
		if( $(this).val() == "login") {
			// login 
			$("#register-form-set").hide();
			$("#login-form-set").show();
			$("#skip-form-set").hide();
			$("#fb-form-set").hide();
		} else if($(this).val() == "register") {
			// register 
			$("#register-form-set").show();
				initCastomForms();
			$("#login-form-set").hide();
			$("#skip-form-set").hide();
			$("#fb-form-set").hide();
		} else if($(this).val() == "skip") {
			$("#register-form-set").hide();
			$("#login-form-set").hide();
			$("#skip-form-set").show();
			$("#fb-form-set").hide();
		} else if($(this).val() == "fb") {
			$("#register-form-set").hide();
			$("#login-form-set").hide();
			$("#skip-form-set").hide();
			$("#fb-form-set").show();			
		}

		
	})
    // login validation
    var validator = $("#login").validate({
        errorLabelContainer: $("#login div.error2")
    });




    // login
    $('#login').submit(function(){  
         if(validator.valid()) {
            $.ajax({
                url: $(this).attr('action'), 
                data: $(this).serialize(),
                type: $(this).attr('method'),
                dataType: 'json',
                success: function(response){
                    if (response['login']==false) {
                        showMessage('Login failed!','Invalid username or password. Try again.','error');
                    } else {
                        window.location = response['forward'];
                    }
                }
            });
        }
        return false;
    });
    
    $('#newslettersubscription').validate();
    
    $('#newslettersubscription').submit(function(){
        $.ajax({
            url: $(this).attr('action'), 
                data: $(this).serialize(),
                type: $(this).attr('method'),
                dataType: 'json',
                success: function(response){
                    if (response['status']==false) {
                        showMessage('Newsletter subscription failed!',$('#newsletteremail').val()+' is already subscribed to our newsletter!','error');
                    } else {
                        showMessage('You have been subscribe to our newsletter successfully.','Thank you for your subscription.','success');
                        $('#newsletterbox').hide('fast');
                    }
             }
        
        });
         return false;
    });
    
    $(".shipping-box input:radio").click(function(){
    	checkShiping($(this).val());
    });


    
    $('#promocode').keypress(function(e){
	    if(e.which == 13){
			e.preventDefault();
			$("#promocode").change();
			return false;
    	}
     });
    
    // for discount code
    $("#promocode").live("change",function(){
    	var promo=$(this).val();
    	if($(this).val().length>3) {
    	
			$.ajax({
		        url:'/cart?shop=promo&code='+promo, 
		            type: 'get',
		            dataType: 'json',
		            success: function(r){
						$("#promocoder").html(r.discount);
		        		$("#price").text(r.price);
		        		$(".totalamount").text(r.price);
		        		if(r.discount == 0) {
			        		$("#promocodediv").hide();		        		
		        		} else {
			        		$("#promocodediv").show();
		        		}
		        		if(r.msg == undefined) {
			        		window.location.reload();
		        		} else {
		        			alert(r.msg);
		        		}
						
		         }
		    
		    });

    	}
    });
    
    swapspan();
    $("#shipping_address").addClass("hidden");
//    if(checkpriceok) {
	    initFB();
  //  }
});

function callpromo(){
	$('#promocode').change();
}

function delpromo(){
	$('#promocode').change();
}


function facebook_onlogin(url) {
	block();
	window.location="/fbc/login?url="+url;
}

function initFB() {
	FB.init(fb_apikey, "/xd_receiver.htm", 
	{ 
		permsToRequestOnConnect : "email"
	}); 
}

// topspan

function swapspan() {

	if($("#toptext span").length < topspan+1) {
		topspan=0;
	} 
	$("#toptext span").hide();
	$("#toptext span").each(function(i){
		if(i == topspan) {
			$(this).fadeIn("slow");

		} 

	});
	topspan=topspan+1;
	setTimeout("swapspan();",8000);
	
}

function checkShiping(mothodid) {

    $.ajax({
        url: base+"cart?shop=checkship&postage_method="+mothodid, 
        data: $("#card-form").serialize(),
        type: 'post',
        dataType: 'json',
        success: function(r){
        		$(".price").fadeOut("fast",function(){

	        		$("#price").text(r.price);
	        		$(".totalamount").text(r.price);
	        		$("#shipping").text(r.shipping);
					$(".price").fadeIn("fast");

        		});


        		


        }
    });
    return false;
}


function removeOrder(orderid,amount) {
	var total=parseInt($("#price").text());
    $.ajax({
        url: base+"cart?shop=removeorder&orderid="+orderid, 
        type: 'post',
        dataType: 'json',
        success: function(r){
    		$(".order_"+orderid).fadeOut("slow",function(){
				$(".order_"+orderid).remove()
    		});
    		// total order - this order
    		$(".totalamount").html(total-amount);
    		
        }
    });
}



function removeImage(imageid) {
    $.ajax({
        url: base+"cart?shop=removeimage&imageid="+imageid, 
        type: 'post',
        dataType: 'json',
        success: function(r){
    		$(".image_"+imageid).fadeOut("slow",function(){
				$(".image_"+imageid).remove()
    		});
    		
        }
    });
}







function checkPrice() {
	if(checkpriceok) {
	    $.ajax({
	        url: base+"cart?shop=checkprice", 
	        data: $("#card-form").serialize(),
	        type: 'post',
	        dataType: 'json',
	        success: function(r){
	        		$(".price").fadeOut("fast",function(){
		        		$("#price").text(r.price);
						$(".price").fadeIn("fast");
	        		});
	        		
	
	
	        }
	    });
    } else {
    	// check the payment shop
    	$(".payforms").hide();
    	$("#"+$("#paymentid").val()).show();
    }
    return false;
}

function fancy() {

 $(".fancy").fancybox({                                                                                                                                        
                        'zoomSpeedIn'	: 0.5,                                                                                                                                 
                        'zoomSpeedOut'	: 0.5,                                                                                                                                 
                        'overlayShow'	: true,                                                                                                                              
                        'padding'       : 5,
                        'overlayOpacity': 0.8,
                        'overlayColor'  : "#000"
     });
}
function pageit(page,gid) {

		$.blockUI({ 
			message: '<img src="/images/pleasewait_btn.png" />' ,
		 css: { 
		        padding:        0, 
		        margin:         0, 
		        width:          '30%', 
		        top:            '40%', 
		        left:           '35%', 
		        textAlign:      'center', 
		        color:          '#000', 
		        border:         '0px solid #aaa', 
		        backgroundColor:'', 
		        cursor:         'wait' 
		    }, 
	});


	var p = page.split("page=")[1];

	$.ajax({
            url: base+"portfolio?gid="+gid+"&page="+p,
                type: "post",
                dataType: 'json',
                success: function(r){
					$(".page_"+gid).html(r.pageing);
					$("#image_"+gid).html(r.images);
	                $.unblockUI();
				   fancy();
          }

    });
}

function coll(){
		

        $("#fancy_div .collapsable").css("border","0px solid").hide();

        $("#fancy_div .collapsable,#fancy_div .collapser").addClass("coll");

        $("#fancy_div .collapsable").click(function(){
                $(this).hide("fast");
        });
        
        $("#fancy_div .collapser").click(function(){
                i = $("#fancy_div .collapser").index(this);
                e = $("#fancy_div .collapsable").eq(i)
                if($(e).is(":visible")) {

                        $(e).slideUp("fast");
                }else {
		                $("#fancy_div .collapsable").slideUp("fast");
                        $(e).slideDown("fast");
                }

        });

}


function block() {

			$.blockUI({ 
					message: '<img src="/images/pleasewait_btn.png" />' ,
				 css: { 
				        padding:        0, 
				        margin:         0, 
				        width:          '30%', 
				        top:            '40%', 
				        left:           '35%', 
				        textAlign:      'center', 
				        color:          '#000', 
				        border:         '0px solid #aaa', 
				        backgroundColor:'', 
				        cursor:         'wait' 
				    }, 
			});
}

/**
    display a message.
    @title = Title of the message
    @message = optional text
    @type = ["notification" | "error" | "success"]
**/
function showMessage(title, message, type) {
        if(type=="success") {
            $("#messageTitle").addClass("successMessage");
            $("#messageTitle").removeClass("errorMessage");
            $("#messageTitle").removeClass("notificaionMessage");
        } else if(type=="notification") {
            $("#messageTitle").addClass("notificationMessage");
            $("#messageTitle").removeClass("errorMessage");
            $("#messageTitle").removeClass("successMessage");
        } else {
            $("#messageTitle").addClass("errorMessage");
            $("#messageTitle").removeClass("notificaionMessage");
            $("#messageTitle").removeClass("successMessage");
        }
        $("#messageTitle").html(title);
        $("#messageBody").html(message);
        $("#ajaxMessage").show("slow");
        /* this cause layout problem in IE7, the active tabs freaking out */
        if(type=="success" || type=="notification") setTimeout('$("#ajaxMessage").hide("slow");', 5000);
}

