// Matthew Hammond
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");

$(document).bind("contextmenu",function(e){
	return false;
});

$(document).ready(function() {
	$("a.menuItem").hover(
			function () {
		        $(this).find("img.droppinga").animate({top: "-0px"},200)
		          .animate({top:"-5px"},50)
		          .animate({top:"-0px"},50);
		      }, 
		      function () {
			        $(this).find("img.droppinga").animate({ 
			            top: "-100px"
			          },500);
			      }
	)
	
	if ($(".datepicker").size()>0){
		$(".datepicker").datepicker({ dateFormat: 'd M y' });
	}
	
	$("#prize-dialog").dialog({
	autoOpen:false, 
	width:800, 
	height: 600, 
	title: "a-Fotografy Questionnaire", 
	zIndex: 100000,
	buttons: {
		"Send": function(){
			var v1 = $("#question #1").val();
			var v2 = $("#question #2").val();
			var v3 = $("#question #3").val();
			var v4 = $("#question #4").val();
			var v5 = $("#question #5").val();
			var v6 = $("#question #6").val();
			var v7 = $("#question #7").val();
			var v8 = $("#question #8").val();
			var v9 = $("#question #9").val();
			var v10 = $("#question #10").val();
			var v11 = $("#question #11").val();
			var v12 = $("#question #12").val();
			var v13 = $("#question #13").val();
			var v14 = $("#question #14").val();
			var v15 = $("#question #15").val();
			
			$.ajax({
				type: "GET",
				url: "/page/questionnaire_proc.php",
				data: "1=" + v1 + "&2=" + v2 + "&3=" + v3 + "&4=" + v4 + "&5=" + v5 +  "&6=" + v6 + "&7=" + v7 + "&8=" + v8 + "&9=" + v9 + "&10=" + v10 + "&11=" + v11 + "&12=" + v12 + "&13=" + v13 + "&14=" + v14 + "&15=" + v15,
				success: function(){
					$("div").dialog("close");
				}
			});
		},
		"Close": function(){
			$(this).dialog("close");
		}	
	}
	});
	
	$("#prize").click(function(){
		$("#prize-dialog").load("/page/questionnaire.php", function(){$('input.submit').hide()});
		$("#prize-dialog").dialog("open");
	});
	
	var $loading = $("<img src='/images/a_fotografy_loading.gif' alt='loading' />");
	
	if ($('.slide a img').length){
		$('.slide a img').mouseover(function(){
		$(this).animate({ opacity:"1.0" },200)});
		$('.slide a img').mouseout(function(){
		$(this).animate({ opacity:"0.5" },200)});
    }
	
	if ($('.scroll-pane').length){
		$('.scroll-pane').jScrollPane();
	}
	
	if ($('a.orders').length){
		$('a.orders').each(function() {
			var $dialog = $('<div></div>').append($loading);
			var $link = $(this).one('click', function() {
				$dialog
					.load($link.attr('href'))
					.dialog({
						title: 'Order Details',
						width: 350,
						height: 350
					});
	
				$link.click(function() {
					$dialog.dialog('open');
	
					return false;
				});
	
				return false;
			});
		});
	}
	
	if ($('#change-password').length){
		
		var $changeDialog = $('#change-password');
		
		$changeDialog.dialog({
			title: 'Change Password',
			width: 350,
			height: 220,
			autoOpen: false,
			buttons: {
				'Close': function(){
					$changeDialog.dialog('close');
				},
				'Save': function(){
					var old = $('#old-password').val();
					var new1 = $('#new-password').val();
					var new2 = $('#new-password-again').val();
					$.ajax({
						url: 'change-password.php',
						data: {old:old,new1:new1,new2:new2},
						type: 'POST',
						success: function(html){
							if (html=="Your password has been changed. "){
								button = $("button:contains('Save')").hide();
							}
							$changeDialog.html(html);
						},
						error: function(){
							$changeDialog.html('Sorry an error has occurred.');
						}
					});
				}
			},
			close: function(){
				$changeDialog.html('<form><label for="email">Enter your email: </label><input id="forgot-email" type="text" name="email" /></form>');
					button = $("button:contains('Send')").show();
			}			
		});
		
		$('#change-password-link').bind('click',function(){
			$changeDialog.dialog('open');
			return false;
		});
	}

	if ($('#forgot-password').length){
		
		var $forgotDialog = $('#forgot-password');
		
		$forgotDialog.dialog({
			title: 'Forgotten Password',
			width: 350,
			height: 55,
			autoOpen: false,
			buttons: {
				'Close': function(){
					$forgotDialog.dialog('close');
				},
				'Send': function(){
					var email = $('#forgot-email').val();
					$.ajax({
						url: 'forgotten.php',
						data: {email:email},
						type: 'POST',
						success: function(html){
							if (html=="Your password has been emailed to you. "){
								button = $("button:contains('Send')").hide();
							}
							$forgotDialog.html(html);
						},
						error: function(){
							$forgotDialog.html('Sorry an error has occurred.');
						}
					});
				}
			},
			close: function(){
				$forgotDialog.html('<form><label for="email">Enter your email: </label><input id="forgot-email" type="text" name="email" /></form>');
					button = $("button:contains('Send')").show();
			}			
		});
		
		$('#forgot-password-link').bind('click',function(){
			$forgotDialog.dialog('open');
			return false;
		});
	}
	
	/*if ($(".title").length) {
		$("div.para.show").show();
		
		$(".title").bind('click',function () {
				$("div.para").hide();
				$("div."+$(this).attr("id")).fadeIn().addClass("show");
				$('.scroll-pane').jScrollPane();
		});
	}*/

	if ($('#product').length || $('.shadowbox').length){
		Shadowbox.init();
	}
	
	if ($('.scroll-pane').length){
		setTimeout(function(){$('.scroll-pane').jScrollPane();},500);
	}
	
	if ($('#mainslideshow').length){
		setInterval( "slideSwitch()", 5000 );
	}
	
	if ($('#slideshow').length){
		setInterval( "slideSwitch()", 5000 );
	}

	if ($('#option-details').length){
		var $liveTip = $('<div class="tooltip-box" id="livetip"></div>').hide().appendTo('body');
		var tipTitle = '',showTip,delay = 100;
		
		$('#option-details').live('mouseover mouseout mousemove', function(event) {
	
			var $img = $('option:selected');
			if (!$img.length) { return; }
				
			if (event.type == 'mouseover') {
				showTip = window.setTimeout(function() {
				  $img.data('tipActive', true);
				  tipTitle = $img.attr('title');
				  $img.attr('title','');
					$liveTip
					.html('<div>' + tipTitle + '</div>')
					.show()
					.css({
					  top: event.pageY + 12,
					  left: event.pageX + 12
					});
				
				}, delay);
			}
				
			if (event.type == 'mouseout') {
				if ($img.data('tipActive')) {
					$img.removeData('tipActive');
					$liveTip.hide();
					$img.attr('title',tipTitle);
				} else {
					window.clearTimeout(showTip);
				}
			}
			
			if (event.type == 'mousemove' && $img.data('tipActive')) {
				$liveTip.css({
					top: event.pageY + 12,
					left: event.pageX + 12
				});
			}
		});
	}

	if ($(".scroll-pane-wide").length){
		$(".scroll-pane-wide").jScrollPane();
	}
		
	if ($("#email-book-selection").length){
		$("#email-book-selection").bind('click',function(){
			$.ajax({
					type: "GET",
					url: "emailbook.php",
					success: function(msg){
					$("#messagefav").show();
					$("#messagefav").text("Success! Selection submitted");
					setTimeout("$('#messagefav').hide();$('#message').text('');",3000);
				},
				error: function(msg){
					$("#messagefav").show();
					$("#messagefav").text("Error! " + msg.status);
					setTimeout("$('#messagefav').hide();$('#message').text('')",3000);
				}
			});
		});
	}

	if ($("#buy").length){
		$("#buy").bind('click',function(){
			$("div.scroll-pane-wide img").each(function(){
				AddToCartFav($(this).attr("id"));
			});
		});
	}
	
	if ($("#delete-books").length){
		$("#delete-books").bind('click',function(){
			$("div.scroll-pane-wide img").each(function(){
				DeleteFav($(this).attr("id"));
			});
			$("#bookCount").text("0");
		});
	
		$("a.delete-book").bind('click',function(){
			var id = $(this).parent("span").prevAll("img").attr("id");
			DeleteFav(id);
			var counter = $("#bookCount").text();
			$("#bookCount").text(parseInt(counter)-1);
		});
	}
	
	if ($("#delete-favourites").length){
		$("#delete-favourites").bind('click',function(){
			$("div.scroll-pane-wide img").each(function(){
				DeleteFav($(this).attr("id"));
			});
			$("#favCount").text("0");
		});
		
		$("a.delete-fav").bind('click',function(){
			var id = $(this).parent("span").prevAll("img").attr("id");
			DeleteFav(id);
			var counter = $("#favCount").text();
			$("#favCount").text(parseInt(counter)-1);
		});
	}
	
	if ($('#galleryNavBar a').length) {
		$('#galleryNavBar a').imgPreview({
			containerID: 'imgPreviewWithStyles',
			srcAttr: 'rel',
			imgCSS: {
				// Limit preview size:
				height: 100
				},
			distanceFromCursor: {top:-130,left:0},
			// When container is shown:
			onShow: function(link){
				// Animate link:
				$(link).stop().animate({opacity:0.4});
				// Reset image:
				//$('img', this).stop().css({opacity:0});
			},
			// When image has loaded:
			onLoad: function(){
				// Animate image
				$(this).animate({opacity:1}, 300);
			},
			// When container hides: 
			onHide: function(link){
				// Animate link:
				$(link).stop().animate({opacity:1});
			}
		});
	}

	if ($('#galleryNavBar a').length){
		$('#galleryNavBar a').mouseover(function(){
			$('#imgPreviewWithStyles').css({opacity:1});
		});
	}
	
	if ($('.datepicker').length){
		$('.datepicker').datepicker();
	}
	
	if ($("form").length){
		$("form").submit(function(){
			$("#loading").show();
		});
	}

	if ($("#dialogPaypal").length){
		$("#dialogPaypal").dialog({ 
			bgiframe: true, 
			autoOpen: false,
			height: 100,
			modal: true,
			title: 'Pay with PayPal',
			resizable: false,
			overlay: {
					opacity: 0.7,
					background: '#7ec244'
			}
		});
	}
	
	if ($("#dialogEdit").length){
		$("#dialogEdit").dialog({ 
			bgiframe: true, 
			autoOpen: false,
			height: 220,
			modal: true,
			title: 'Edit Order',
			resizable: false,
			overlay: {
					opacity: 0.7,
					background: '#7ec244'
			},
			close: function() {
				$("#dialogEdit input").removeClass('ui-state-error');
			},
			draggable: false
		});
	}
	
	if ($(".edit-cart").length){
		$(".edit-cart").bind('click',function(){
			editOrder($(this).attr("id"));
		});
	}
	
	if ($(".delete-cart").length){
		$(".delete-cart").bind('click',function(){
			var id=$(this).attr("id");
			id=id.replace("delete","");
			
			$.ajax({
					type: "GET",
					url: "deletecart.php",
					data: "id="+id,
				success: function(msg){
					location.reload(true);
				},
				error: function(msg){
					//updateTips("Sorry an error has occurred...Please try again.");
				}
			});
		});
	}
	
	if ($('.scroll-pane').length){
		setTimeout(function(){$('.scroll-pane').jScrollPane();},1000);
	}
	
	if ($("#validateTips").length){
		tips = $("#validateTips");
		
		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}
	}
	
	if ($('.receive').length){
		$('.receive input').bind('click',function(){
			if ($(this).is(':checked')){
				var email = 1;
				var message = "You have switched on email alerts.";
			} else {
				var email = 0;
				var message = "You have switched off email alerts.";
			}
			$.ajax({
				url: 'receive_email.php',
				data: { email: email },
				type: 'POST',
				success: function(){
					$('.receive p').html(message);
				}
			});
		});
	}
	
});//End doc ready

function checkRegexp(o,regexp,n) {
	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('ui-state-error');
		updateTips(n);
		return false;
	} else {
		return true;
	}
}

function AddToCartFav(id){
    $.ajax({
            type: "GET",
            url: "../clients/addtocart.php",
            data: "image=" + id + "&size=8&quantity=1",
        success: function(msg){
            $("#message").show();
            $("#message").text("Success! Added to Cart");
            setTimeout("$('#message').hide();$('#message').text('');",3000);
        },
        error: function(msg){
            $("#message").show();
            $("#message").text("Error! " + msg.status);
            setTimeout("$('#message').hide();$('#message').text('')",3000);
        }
    });
} 

function editOrder(editid){
	var id = editid.replace("edit","");
	
	$("#dialogEdit").dialog('option', 'buttons', 
			{
				'Make changes': function() {
				var bValid = true;
				var quantity = $("#quantity");
				//allFields.removeClass('ui-state-error');

				bValid = bValid && checkRegexp(quantity,/^[0-9]/,"Quantity must be a number.");
				
					if (bValid) {
						//post AJAX
						$.ajax({
								type: "GET",
								url: "updatecart.php",
								data: "&id="+id+"&size="+$("#size").val()+"&quantity="+$("#quantity").val(),
							success: function(msg){
								$(this).dialog('close');
								//alert("Success");
								location.reload(true);
							},
							error: function(msg){
								updateTips("Sorry an error has occurred...Please try again.");
							}
						});
					}
				},
				Cancel: function() {
					$(this).children("*").removeClass('ui-state-error');
					$(this).dialog('close');
				}
			}); 
	
	$("#dialogEdit").dialog("open");
	
}
	
function slideSwitch() {
    var $active = $('#slideshow img.active');

    if ( $active.length == 0 ) $active = $('#slideshow img.protect:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next() : $('#slideshow img.protect:first');

    // uncomment the 3 lines below to pull the images in random order
    
    //var $sibs  = $active.siblings();
    //var rndNum = Math.floor(Math.random() * $sibs.length );
    //var $next  = $( $sibs[ rndNum ] );


    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$('img').ready(function(){
	$('#loading').remove();
});

function DeleteFav(img_id){
	$.ajax({
		url: "delete.php",
		type: 'POST',
		data: {img:img_id},
		success: function(response){
			$("div.scroll-pane-wide").find("img#"+img_id).parent().remove();
		}
	});
}

function ShowImageGallery(id){
	$('#mainslideshow img.protect').fadeOut(200);
	setTimeout(function(){$(id).fadeIn(1000);},300);
	$('#imgPreviewWithStyles').css({opacity:0});
}

function BlindRight(div){
	$(div).show("blind", { direction: "right" }, 2000);
	setTimeout("$('" + div + " img').animate({opacity: 1.0}, 100);",1500);
	setTimeout("$('" + div + "').fadeOut(500);",5000);
}

function BlindLeft(div){
	$(div).hide("blind", { direction: "left" }, 2000);
}

function Fade(div){
	$(div).fadeOut("slow")
}

function showSubMenu()
{
	if ( $("#submenu").is(':hidden') ) { 
        $("#submenu").fadeIn(); 
	}
}

function hideSubMenu()
{
	if ( $("#submenu").is(':visible') ) { 
        $("#submenu").fadeOut(); 
	}	
}
