/* function to align something vertically center */
(function ($) {
	$.fn.vCentered = function() {
		// Apply to all selected tags
		return this.each(function(i){
			var childHeight = $(this).height();
			var parentHeight = $(this).parent().height();
			var currentTop = Math.ceil((parentHeight - childHeight) / 2);

			//alert (childHeight + ", " + parentHeight + ", " + currentTop);

			// Apply only if the child element is smaller than parent
			if(currentTop > 0) {
				$(this).css('margin-top', currentTop);
			} else {
				$(this).css('margin-top', 0);
			}
		});
	};

	$.fn.hCentered = function() {
		// Apply to all selected tags
		return this.each(function(i){
			var childWidth = $(this).width();
			var parentWidth = $(this).parent().width();
			var currentLeft = Math.ceil((parentWidth - childWidth) / 2);

			// Apply only if the child element is smaller than parent
			if(currentLeft > 0) {
				$(this).css('margin-left', currentLeft);
			} else {
				$(this).css('margin-left', 0);
			}
		});
	};	
})(jQuery);


/*
	Functions for slide show
*/
var imageWidth;
var imageHeight;
var containerfWidth;
var containerfHeight;
var galleryNavBinded = false;

function slideSwitch() {
    var $active = $('#slideshow DIV.active');

	//$('#slideshow DIV').css({opacity: 0.0});


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

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

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

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

$(function() {
    setInterval( "slideSwitch()", 7000 );
});

// End of functions for slide show.


function loadPage(url)
{
	location.href = url;
}

// Disable draging of image
//$(document).bind('dragstart', function(event) { return true; });

// Display right click menu and show custom menu
$(document).bind("contextmenu",function(event){
	return false;
});


function disableDragging(everything) {
    //$("img, div, span, nav, input").mousedown(function(event){
    //    event.preventDefault();
	//});

    if (everything == true) {
        $("img, div, span, nav").mousedown(function(event){
            event.preventDefault();
	    });
    } else {
        $("img, nav, #logoBox, h1, p, label, span, br").mousedown(function(event){
            event.preventDefault();
        });

        //$("").mousedown(function(event) {
        //    event.preventDefault();
        //});
    }
}

var sPage;

$(document).ready(function(){
	var sPath = window.location.pathname;
	sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

	// Disable text selection in Microsoft IE
	document.onselectstart = function(){return false; }

	
	// Remove the class and id from contents of sitemap dialog
	$("#sitemapDialog nav").removeAttr("id");
	$("#sitemapDialog nav").removeAttr("class");
	
	
	// Code for global horizental drop down navigation
		$(".navigation .mauMenu").hover(
		function () {
			// Show sub menu
			//$(this).find("ul:first").stop().fadeIn(2000);
			//$(this).find("ul:first").dequeue();
			$(".navigation ul ul").stop(true, true).fadeOut(500);
			$(this).find("ul:first").stop(true, true).fadeIn(500);
		},
		function () {
			// Hide sub menu
			//$(this).find("ul:first").stop().fadeOut(10000);
			$(this).find("ul:first").stop(true, true).fadeOut(10000);
		});

    // Disable dragging of everything if it is not contact page
    //  shopping kart may be the exceptions
    if (sPage != "contact.php") {
        disableDragging(true);
    } else {
        disableDragging(false);
    }

    if (sPage == "contact.php") {
        // Make two boxes vertically centered
        $("#contactUs").vCentered();
		var contactUsTop = $("#contactUs").offset().top;
		$("#joinUs").offset({"top" : contactUsTop});

        $("#contactUs, #joinUs").css("opacity", 1);

	    $(window).bind('resize', function(){
	    	$("#contactUs").vCentered();
			contactUsTop = $("#contactUs").offset().top;
			$("#joinUs").offset({"top" : contactUsTop});
	    });
    }

	// NOTE: filter so that it only appears on map page
	// Google map
		if (sPage == "boutique.php")
		{

				var bb_center = new google.maps.LatLng(-33.898851,151.17776);

			    var myOptions = {
				  zoom: 16,
				  center: bb_center,
				  mapTypeId: google.maps.MapTypeId.ROADMAP
				}
				var map = new google.maps.Map(document.getElementById("map_canvas"),
											  myOptions);

				var image = 'images/map_bb_marker.png';
				var myLatLng = bb_center;
				var beachMarker = new google.maps.Marker({
					position: myLatLng,
					map: map,
					icon: image
				});
		}
	// end of google map


	if (sPage == "workmanship.php") {
		function positionWorkmanshipElements() {
			$("#bodyContainer").vCentered();
			$("#bodyContainer").hCentered();
			
			var elem = $("#fadein_right_top");
			var pare = elem.parent().height();
			var vgap = (pare - elem.height() * 2) / 3 + 8;
			
			elem.css("top", vgap);
			$("#fadein_right_bottom").css("bottom", vgap);
		}
	
		positionWorkmanshipElements();
        
	    $(window).bind('resize', function(){
			positionWorkmanshipElements();
	    });

	    // slide show
		$(function(){
			$('#fadein_left img:gt(0)').hide();
			setInterval(function(){$('#fadein_left :first-child').fadeOut(4000).next('img').fadeIn(4000).end().appendTo('#fadein_left');}, 12000);

			$('#fadein_right_top img:gt(0)').hide();
			setInterval(function(){$('#fadein_right_top :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('#fadein_right_top');}, 8000);

			$('#fadein_right_bottom img:gt(0)').hide();
			setInterval(function(){$('#fadein_right_bottom :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('#fadein_right_bottom');}, 6000);
		});
	}
	
	if (sPage == "designstudio.php") {
		function positionDSElements() {
			var imgSize = $("#imgDesignStudio").height();
			var imgLeft = parseInt($(document).width() / 2) - imgSize;
			$("#imgDesignStudio").css("margin-left", imgLeft);
			$("#dsRHS").vCentered();
		}
	
		positionDSElements();
		
		$(window).bind('resize', function(){
			positionDSElements();
	    });
	}

	if (sPage == "services.php") {
	    $("#services_nav a").click(function(){
	    	var descriptionHTML = $(this).find('span').html();
	    	var imgSrc = $(this).find('p').html();

			var servicesHeading = $(this).find('.services_heading').html();
			$("#services_heading").html(servicesHeading);
			
			var servicesDescription = $(this).find('.services_desc').html();
			$("#services_desc").html(servicesDescription);

			$("#services_body").css("opacity", 0);
			
			if (imgSrc != "") {
				var imgSize = $("#services_nav").height() - 10;
			
				$("#services_body img").attr('src', 'images/services/' + imgSrc);
				$("#services_body img").css("width",  imgSize);
				$("#services_body img").css("height", imgSize);
				$("#services_body img").css("display", "inline");		

			} else {
				$("#services_body img").css("width", "0");
				$("#services_body img").css("height", "0");
				$("#services_body img").css("display", "none");
			}
			
			$("#services_body").stop(true, false).animate({
				"opacity": 1
			}, 2000);
			
			var imgWidth = $("#services_body .imgLeft").width();
			var parentWidth = $("#services_body").width();
			
			var textWidth = 500 - $("#services_body .imgLeft").width() - 50;
			$("#services_desc").width(textWidth);

	    	$("#services_desc").vCentered();
	    });
		
		//var menuHeight = $("#services_nav").height();
		//$("#services_nav .imgSrc").load(height(menuHeight));
	}

	if (sPage == "index.php" || sPage == "") {
		function positionImages() {
			var imgHeight = $("#slideshow div").height();
			var imgWidth = imgHeight * 0.85;
		
			$("#slideshow div").hCentered();
			$("#slideshow div").vCentered();
			//$("#slideshow div").css("width", imgWidth);
		}
	
		positionImages();
		
		$("#slideshow").css("left", "400");
		
		var maalImage = $('#slideshow .active img');
		
		maalImage.load(function(){
			var imgLeft	 = parseInt(maalImage.width() / 2);
			$('#slideshow img').css("left", -imgLeft);
		});

	    $(window).bind('resize', function(){
			positionImages();
	    });
	}
	
	if (sPage == "ourworld.php") {
		$(".ourWorldVideo").vCentered();
		$(".ourWorldVideo").hCentered();
		
		$(window).bind('resize', function(){
			$("#ourWorldVideo").hCentered();
			$("#ourWorldVideo").vCentered();
	    });
	}

	if (sPage == "boutique.php") {
		$("#map_canvas").vCentered();
		$("#boutiqueInfo").vCentered();

	    $(window).bind('resize', function(){
			$("#map_canvas").vCentered();
			$("#boutiqueInfo").vCentered();
	    });

	    $("#printMap").click(function(){
            printMap();
	    });

		function printMap() {
            var mywindow = window.open('', '', 'height=920,width=700,scrollbars=yes', false);
            mywindow.document.write('<html><head><title>BB Designer Jewellers</title>');
            mywindow.document.write('</head><body >');
            mywindow.document.write('<img src = "images/map.jpg" />');
            mywindow.document.write('</body></html>');

            mywindow.print();
            //mywindow.close();
            return true;
		}
	}

	if (sPage == "history.php") {
		$("#vartan #imgVartan").hCentered();
		$("#levon #imgLevon").hCentered();

		var body_layout_top = parseInt($("#body_layout2").offset().top);
		var body_layout_left = parseInt($("#body_layout2").offset().left);
		$("#AboutUs").offset({"top": body_layout_top - 50, "left": body_layout_left});

		$(window).bind('resize', function(){
			$("#vartan #imgVartan").hCentered();
			$("#levon #imgLevon").hCentered();
            $("#AboutUs").offset({"top": parseInt($("#body_layout2").offset().top) - 50, "left": parseInt($("#body_layout2").offset().left)});
		});
	}
	
	$("#closePolicyDialog").click(function(){
		$("#policyStatement").fadeOut("slow");
	});

	$("#closeSitemapDialog").click(function(){
		$("#sitemapDialog").fadeOut("slow");
	});
});

$(window).load(function() {
	if (sPage == "history.php" || sPage == "workmanship.php") {
		$("#historyBody").mCustomScrollbar("vertical",0,"swing",1.05,"fixed","yes","no",0);
		$("#workmanshipBody").mCustomScrollbar("vertical",0,"swing",1.05,"fixed","yes","no",0);
	}
});

function showPolicy() {
	$("#policyStatement").fadeIn("slow");
}

function showSiteMap() {
	$("#sitemapDialog").fadeIn("slow");
}

function loadGallery() {
	var galleryHTML = "";
	$.each(myGallery, function(index) {
		galleryHTML += "<div class = 'galleryImage'><img id = \"galleryImg" + (index + 1) + "\" class = 'img_galleryImage' alt = \"" + myGallery[index][1] + "\" /></div>";
		//galleryHTML += "<div class = 'galleryImage'><img id = \"galleryImg" + (index + 1) + "\" class = 'img_galleryImage' alt = \"" + myGallery[index][1] + "\" /></div><input type = 'hidden' id = 'gal_id" + (index + 1) + "' value = '" + myGallery[index][2] + "'";
		//galleryHTML += "<div class = 'galleryImage'></div>";
	});
	$("#galleryBox").html(galleryHTML);

	// Get a load of this - Microsoft Internet Explorer can't render alpha transparent PNG images with opacity
	//	so it needs a bit of hacking here.
	
		// if ie 7 or 8
		if($.browser.msie && ($.browser.version == "8.0" || $.browser.version == "7.0")) {
			$(".galleryImage img").each(function(index, domEle) {
				$(domEle).css({filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/" + myGallery[index][0] + "', sizingMethod='scale')"});
				$(domEle).attr('src', 'images/empty.gif');
			});
		} else {	// If other browsers
			$(".galleryImage img").each(function(index, domEle) {
				$(domEle).attr('src', 'images/' + myGallery[index][0]);
			});
		}
	
	$(".galleryImage").hCentered();
	
	$(window).bind('resize', function(){
		$(".galleryImage").hCentered();
	});
	
	if (!galleryNavBinded) {
		// Start of functions to navigate around
		$("#next").click(function(){
			showImage(++activeImage, 300);
		});

		$("#previous").click(function(){
			showImage(--activeImage, 300);
		});

		$('#galleryBox').bind('mousewheel', function(event, delta) {
			activeImage = delta > 0 ? --activeImage : ++activeImage;
			showImage(activeImage, 250);
			return false;
		});
		// end of functions to navigate around
		
		galleryNavBinded = true;
	}

	showImage(activeImage, 300);
}



function changeCat(newCatName) {
	myGallery = new Array();
	var firstIndex = 0;
	
	for (var i = 0; i < myGrandGallery.length; ++i) {
		if (myGrandGallery[i][4] != newCatName) continue;
	
		//for (var j = 0; j < 5; j++) {
			myGallery[firstIndex] = new Array(
				myGrandGallery[i][0],
				myGrandGallery[i][1],
				myGrandGallery[i][2],
				myGrandGallery[i][3],
				myGrandGallery[i][4]
			);
		//}
		
		firstIndex++;
	}
	
	totalImages = myGallery.length;
	
	activeImage = 1;
	loadGallery();
}

function showImage(imageIndex, speed)
{
	// Just to make sure activeImage is within the range
	if (activeImage > totalImages) {
		activeImage = totalImages;
		return;
	}
	if (activeImage < 1) {
		activeImage = 1;
		return;
	}

	var maalOpacity = 1.0;
	var maalHeight = 200;
	var maalWidth = 200;
	var deltaSize = 0.2;
	var deltaTop = 1.5;

	var gap = 25;

	// Show the main banana first
	var maal = $(".galleryImage:nth-child(" + imageIndex + ")");
	var maalLeft = 0;
	var maalTop = 80;
	maal.stop(true, false).animate({
		opacity: maalOpacity,
		left: maalLeft,
		top: maalTop,
		height: maalHeight,
		width: maalWidth
	}
	,speed, function() {
		if (!($.browser.msie && ($.browser.version == "8.0" || $.browser.version == "7.0"))) {
			for (var i = imageIndex - 2; i <= imageIndex + 2; ++i) {
				// First of all filter to make sure the images are not out of bound
				if (i > 0 && i <= totalImages) {
					var absDiff = Math.abs(imageIndex - i);
					
					Pixastic.revert(document.getElementById("galleryImg" + i));
			        
					if (i != imageIndex) {
						$("#galleryImg" + i).pixastic("blurfast", {amount: absDiff / 10});
					}
				}
			}
		}
	});
	
	maal.children("img").css("marginLeft", 0);

	var bluryLeft = 0;

	// Show bananas on the left
	var imgIndex = 0;
	for (var i = imageIndex - 1; i >= 1; --i) {
		imgIndex++;
		if (imgIndex == 4) break;
		
		var tmpMaal = $(".galleryImage:nth-child(" + i + ")");
		var maalOnRight = $(".galleryImage:nth-child(" + (i + 1) + ")");

		maalOpacity -= 0.33;
		maalHeight -= parseInt(maalHeight * deltaSize);
		maalWidth -= parseInt(maalWidth * deltaSize);
		maalTop -= parseInt(12 * deltaTop);
		if (maalHeight < 0) maalHeight = 0;
		if (maalWidth < 0) maalWidth = 0;

		maalLeft -= maalWidth + gap;

		tmpMaal.stop(true, false).animate({
			opacity: maalOpacity,
			left: maalLeft,
			top: maalTop,
			height: maalHeight,
			width: maalWidth
		}
		, speed);
		
		//bluryLeft = imgIndex * maalWidth * deltaSize * -1;
		//tmpMaal.children("img").css("marginLeft", bluryLeft);
		//tmpMaal.children("img").css("marginLeft", 0);

		deltaTop += 2;
	}

	// Reset properties
	maalOpacity = 1.0;
	maalHeight = 200;
	maalWidth = 200;
	maalTop = 80;
	deltaTop = 1;
	bluryLeft = 0;

	// Change maalLeft to be center of parent + half the width of active image
	//maalLeft = parseInt(($("#galleryBox").width() + maalWidth) / 2);
	maalLeft = 200 + gap;

	// Show bananas on the right
	imgIndex = 0;
	for (var i = imageIndex + 1; i <= totalImages; ++i) {
		imgIndex++;
		if (imgIndex == 4) break;
	
		var tmpMaal = $(".galleryImage:nth-child(" + i + ")");
		var maalOnLeft = $(".galleryImage:nth-child(" + (i - 1) + ")");

		maalOpacity -= 0.33;
		maalHeight -= parseInt(maalHeight * deltaSize);
		maalWidth -= parseInt(maalWidth * deltaSize);
		maalTop -= parseInt(15 * deltaTop);
		if (maalHeight < 0) maalHeight = 0;
		if (maalWidth < 0) maalWidth = 0;

		tmpMaal.stop(true, false).animate({
			opacity: maalOpacity,
			left: maalLeft,
			top: maalTop,
			height: maalHeight,
			width: maalWidth
		}
		, speed);

		maalLeft += maalWidth + gap;
		deltaTop += 2;
		
		//bluryLeft = imgIndex * maalWidth * -1;
		//tmpMaal.children("img").css("marginLeft", 0);
	}

	showImageInfo(imageIndex, speed);
	showLoveCount(imageIndex);
}

function showLoveCount(imageIndex) {
	$("#loveCounter span").html(myGallery[imageIndex - 1][3]);
}

function showImageInfo(imageIndex, speed)
{
	$("#galleryMessage").css({ opacity: 0 });
	$("#galleryMessage").html(myGallery[imageIndex - 1][1]);
	$("#galleryMessage").animate({ opacity: 1 }, speed);
}

// Function to align anything vertically middle
function verticallyAlign(which, childHeight) {
	which.css("marginTop", childHeight / 2 * -1);
}
// 9807 2712
