/*
	Alive Custom Javascript
	Author: Spacehead Concepts (http://www.spaceheadconcepts.com)
*/

//THEME SETUP//////////////////////////////////////////////////////////////
/*init-------------------------------------------------------------------*/
var hoverIconWidth = 115; //Image hover icon width in pixels

/*tiles-------------------------------------------------------------------*/
var tileSlideSpeed = 500; //speed of tile slide animation - possible values: 'slow', 'normal', 'fast', or in milliseconds
var tileSpeed = 4000; //Tile slide update speed in milliseconds
var tileSmall = 100; //Tile height for nav in pixels
var tileLarge = 180; //Tile height for home in pixels

/*supersized-------------------------------------------------------------*/
var pauseOnContent = true; // Pause background slideshow when content opens

/*twitter details--------------------------------------------------------*/
var twitterAccount = "giafrese"; // Your twitter account name
var numTweets = "5"; //Number of tweets to display

/*Fancybox details----------------------------------------------------------*/
var lightboxTransition = 'fade'; //Set lightbox transition type
var overlayOpacity = 0.8; //Fancybox overlay opacity
var overlayColor = '#000'; //Fancybox overlay color	
var videoWidth = 750; //Fancybox video width
var videoHeight = 385; //Fancybox video height

/*toggle/fade speeds-----------------------------------------------------*/
var hoverFadeSpeed = 400; //Image icon hover speed - possible values: 'slow', 'normal', 'fast', or in milliseconds
var pageFadeSpeed = 400; //speed of page fading animation - possible values: 'slow', 'normal', 'fast', or in milliseconds
var menuToggleSpeed = 400; //Menu toggle speed - possible values: 'slow', 'normal', 'fast', or in milliseconds
var menuEase = 'easeInOutQuart'; //Ease type
var pageEase = 'easeInCubic'; //Ease type

/*Contact form messages----------------------------------------------------*/
var formError = "There was an error sending your email. Please try again.";
var formWarning = "Verify fields and try again!";
var formSuccess = "Thanks, we got your email and will respond as soon as possible.";
var formSuccessTitle = "Message sent.";
var formReload = "Send any enquiry you may have using the form below.";
var formReloadTitle = "Send your enquiry";

//END SETUP//////////////////////////////////////////////////////////////////

jQuery.noConflict();
(function ($) {	

    $(document).ready(function () {

        var widthRef;
        var tileArray = new Array();
        var pageArray = new Array();
        var prevPage;
        var nextPage;
        var currentTile;
        var contentLeftPos = $("#contentWrapper").css("left");
        var interval;


        $("#wrapper").hide().css({
            "opacity": 0
        });

       

        function Tile(element, index) {
            this.element = element; //DOM element entire tile
            this.content = $(this.element).find(".tileContent"); //DOM element tile content
            this.position = 0; //0 : top, 1 : middle, 2 : bottom
            this.size = 0; //0 : home, 1 : nav
            this.index = index;
            this.submenu = null;
            this.submenuDisplay = false;

            this.isHighlight = function () {
                return $(this.element).hasClass("highlight");
            }

            this.setHighlight = function () {
                $(this.element).addClass("highlight");
            }

            this.removeHighlight = function () {
                $(this.element).removeClass("highlight");
            }

            this.headingHeight = function () {
                var h = $(this.element).find(".tileHeading").outerHeight(true);
                return h;
            };

            this.nextPosition = function () {
                this.position++;
                if (this.position > 2) {
                    this.position = 0;
                }
            };

            this.midPosition = function () {
                this.position = 1;
            }

            this.hover = function () {
                var h = this.tileHeight();
                var p = h / 2 + h * 0.1 - this.headingHeight();
                return p;
            };

            this.top = function () {
                var h = this.tileHeight() / 2;
                var t = h * this.position - this.headingHeight();
                return t;
            };

            this.tileTop = function () {
                var t = $(this.element).css("top");
                return t;
            };

            this.tileLeft = function () {
                var l = $(this.element).css("left");
                return l;
            };

            this.tileHeight = function () {
                var h;
                if (this.size == 0) {
                    h = tileLarge;
                } else {
                    h = tileSmall;
                }
                return h;
            };


            this.toggleSubmenu = function () {
                var tile = this;
                if (this.submenuDisplay == false) {
                    //do show submenu 
                    if (tile.submenu != null) {
                        tile.submenuDisplay = true;
                        $(tile.element).find(".main").animate({
                            "opacity": 0
                        }, {
                            duration: tileSlideSpeed,
                            queue: true,
                            complete: function () {
                                $(this).hide();
                                $(tile.submenu).show();
                                $(tile.submenu).animate({
                                    "opacity": 1
                                }, {
                                    duration: tileSlideSpeed,
                                    complete: function () {
                                        $(tile.element).bind('mousemove.submenu', function (e) {
                                            var top = (($(this).offset().top - $("#wrapper").scrollTop() - e.pageY) * ($(tile.submenu).outerHeight(true) - tileSmall) / tileSmall);

                                            $(tile.submenu).stop().animate({
                                                'top': top
                                            }, {
                                                duration: 150
                                            });
                                        });
                                    }
                                });

                            }
                        });
                    }
                } else {
                    //do hide function
                    tile.submenuDisplay = false;
                    if (tile.submenu != null) {
                        $(tile.element).unbind('mousemove.submenu');
                        $(tile.submenu).find("a").each(function () {
                            $(this).removeClass("active");

                        });


                        $(tile.submenu).animate({
                            "opacity": 0
                        }, {
                            duration: tileSlideSpeed,
                            queue: true,
                            complete: function () {

                                $(this).hide();
                                $(this).css({
                                    "top": 0
                                });
                                $(tile.element).find(".main").show();
                                $(tile.element).find(".main").animate({
                                    "opacity": 1
                                }, {
                                    duration: tileSlideSpeed,
                                    queue: true
                                });
                            }



                        });
                    }
                }
            };

            this.setSubmenu = function () {
                if (this.submenu != null) {
                    var tile = this;

                    $(tile.submenu).find("a").each(function (index) {

                        $(this).bind('click.subnav', function () {

                            changePage(tile, index);
                            $(this).siblings().removeClass("active");
                            $(this).addClass("active");

                        });

                    });
                }
            };

        }



        function generateRandomNumber() {
            result = Math.floor(Math.random() * tileArray.length);
            if (result < 0) {
                result = 0;
            } else if (result > tileArray.length - 1) {
                result = tileArray.length - 1;
            }
            return result;
        }

        function moveLiveTiles() {

            var rand = generateRandomNumber();
            if (!tileArray[rand].isHighlight()) {
                tileArray[rand].nextPosition();
                tileAnimation(tileArray[rand]);
            }

        }

        function tileAnimation(tile, pos) {
            if (pos == null) {
                pos = tile.top();
            }
            $(tile.content).animate({
                "top": pos
            }, tileSlideSpeed);
        }

        function removeHighlight() {
            $(tileArray).each(function (index) {
                this.removeHighlight();
            });
        }

        function tileEvents(tile) {


            $(tile.element).hover(

            function () {
                if (tile.submenuDisplay == false) {

                    tileAnimation(tile, tile.hover());
                }
                clearInterval(interval);
            }, function () {

                if (tile.isHighlight()) {
                    tile.midPosition();
                }


                tileAnimation(tile);

                interval = setInterval(moveLiveTiles, tileSpeed);
            });


            $(tile.element).bind('click.highlight', function () {

                if ($(tile.element).hasClass("external")) {
                	return true;
                    
                }

                if (tile.size == 0) {
                    prevPage = null;
                    nextPage = null;
                    currentTile = null;
                    updateTileSize(1);
                    refreshTiles();
					
					$("#logo.home, #logo.home *").switchClass("home", "nav", menuToggleSpeed, menuEase);
                   // $("#logo.home").find("*").switchClass("home", "nav", menuToggleSpeed, menuEase);
					
                    $(".tile.home").each(function (ind) {
                    	$(this).find(".home").toggleClass("home nav");
                        $(this).switchClass("home", "nav", menuToggleSpeed + ind * 150, menuEase, function () {
							
                            if (ind == 5) {
                                $("#tileBlock.home").toggleClass("home nav");
                                showPageContent(tile);
                            }

                        });


                    });

                }

                $("html").animate({
                    scrollTop: 0
                }, tileSlideSpeed);

                if (currentTile != tile.index) {
                    removeHighlight();
                    tile.setHighlight();
                    tile.toggleSubmenu();
                    if (currentTile != null) {
                        tileArray[currentTile].toggleSubmenu();
                    }

                    currentTile = tile.index;
                    changePage(tile);


                }

                return false;
            });


        }

        function updateTileSize(size) {
            $(tileArray).each(function (index) {
                this.size = size;

            });

        }

        function refreshTiles() {
            $(tileArray).each(function (index) {
                tileAnimation(this);
            });
        }


        function getPageIndex(mainIndex, subIndex) {
            if (subIndex != null) {
                return mainIndex + "-" + subIndex;

            } else {
                return mainIndex;
            }
        }

        function changePage(tile, subpage) {

            nextPage = "#page" + getPageIndex(tile.index, subpage);

            if (prevPage == null) {
                showPage(nextPage);
            } else {
                hidePage(prevPage);
            }

            prevPage = nextPage;



        }

        function showPage(page) {

            $(page).show();
            $(page).animate({
                opacity: 1
            }, {
                duration: pageFadeSpeed,
                easing: pageEase,
                queue: true
            });

        }

        function hidePage(page, noNext) {

            $(page).animate({
                opacity: 0
            }, {
                duration: pageFadeSpeed,
                easing: pageEase,
                queue: true,
                complete: function () {
                    $(page).hide();
                    if (noNext == null) {
                        showPage(nextPage);
                    }
                }
            });
        }

        function showPageContent() {

            $("#contentWrapper").show().css({
                "left": 500
            });
            
            if(pauseOnContent == true) { api.playToggle(); }
            $("#contentWrapper").animate({
                opacity: 1.0,
                left: contentLeftPos,
                top: 0
            }, {
                duration: tileSlideSpeed,
                easing: pageEase,
                queue: true
            });

        }


        function hidePageContent() {


            if(currentTile != null) { $(tileArray[currentTile].submenu).children().removeClass("active");}

            $("#contentWrapper").stop().animate({
                opacity: 0.0,
                left: 500,
                top: 0
            }, {
                duration: tileSlideSpeed,
                easing: pageEase,
                queue: true,
                complete: function () {
                    $("#contentWrapper").hide();
                    $(prevPage).hide();
                    if(pauseOnContent == true) {api.playToggle();}
                    if (currentTile != null) {
                        tileArray[currentTile].toggleSubmenu();
                        $("#tileBlock.nav").toggleClass("nav home");
                        $("#logo.nav, #logo.nav *").switchClass("nav", "home", menuToggleSpeed, menuEase);
                    	//$("#logo.nav").find("*").switchClass("nav", "home", menuToggleSpeed, menuEase);
                        $(".tile.nav").each(function (ind) {
                            $(this).find(".nav").toggleClass("nav home");
                            $(this).switchClass("nav", "home", menuToggleSpeed + ind * 100, menuEase, function () {

                            });
                        });
                    }
                }
            });
        }



        function logoEvents() {   
            $("#logo").click(function () {
            	if($(this).hasClass("nav")){
                	updateTileSize(0);
                	refreshTiles();
                	removeHighlight();
                	hidePageContent();
                	return false;
             	}
            });
        }



        function setWrapperVertical() {
            var viewport = viewportDimensions();
            var topPos = viewport[1];
            topPos = (topPos - $('#tileBlock').height()) / 2;
            if (topPos < 0) topPos = 0;
            $('#tileBlock').css({
                'top': topPos
            });
        }

        function viewportDimensions() {
            var viewportwidth;
            var viewportheight;

            if (typeof $(window).innerWidth() != 'undefined') {
                viewportwidth = $(window).innerWidth();
                viewportheight = $(window).innerHeight();
            }

            var dimensions = new Array(viewportwidth, viewportheight);
            return dimensions;

        }

        function initTiles() {

            var obj = $("#tileBlock .tile");
            $(obj).each(function (index) {
                tileArray[index] = new Tile(this, index);
                $(this).find(".submenu").each(function (ind) {
                    tileArray[index].submenu = this;
                    tileArray[index].setSubmenu();
                });



                tileEvents(tileArray[index]);
                $(this).addClass("home");
                $(this).find('*').addClass("home");
            });
            
            $("#logo").addClass("home");
            $("#logo").find('*').addClass("home");
            
            //bindClickNav();
        }

        function initPages() {

            var obj = $("#contentWrapper .page");
            $(obj).each(function (index) {
                $(this).find(".mainpage").each(function (ind) {
                    $(this).attr("id", "page" + index);
                });

                $(this).find(".subpage").each(function (ind) {
                    $(this).attr("id", "page" + index + "-" + ind);

                });
            });

        }

        setWrapperVertical();
        initTiles();
        initPages();
        logoEvents();


        $(window).load(function () {

            $("#preloader").animate({
                "opacity": 0
            }, {
                duration: 500,
                complete: function () {
                    $("#preloader").hide();
                    $("#wrapper").show().animate({
                        "opacity": 1
                    }, {
                        duration: pageFadeSpeed,
                        complete: function () {
                            refreshTiles();
                            interval = setInterval(moveLiveTiles, 4000);
                        }
                    });
                }
            });

        });

        $(window).resize(function () {

            setWrapperVertical();

        });




        //init fancybox - image handling
        $("a._imageOriginal").fancybox({
            'transitionIn': lightboxTransition,
            'transitionOut': lightboxTransition,
            'titlePosition': 'over',
            'padding': '0',
            'overlayOpacity': overlayOpacity,
            'overlayColor': overlayColor,
            'titleFormat': function (title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
            }
        });

        //init fancybox - video handling
        $("a._videoOriginal").fancybox({
            'transitionIn': lightboxTransition,
            'transitionOut': lightboxTransition,
            'padding': '0',
            'width': videoWidth,
            'height': videoHeight,
            'overlayOpacity': overlayOpacity,
            'overlayColor': overlayColor,
            'autoscale': 'true',
            'type': 'swf',
            'swf': {
                'wmode': 'transparent',
                'allowfullscreen': 'true'
            }

        });



        //set rollover initial opacity
        $("._rollover").css({
            "opacity": "0"
        });
        $("._mediaIcon").css({
            "opacity": "0"
        });


        //iterrate over all image frames - set hover w/h, shadow w/h
        $(".imageFrame").each(function () {


            var imgWidth = $(this).children('img').width();
            var imgHeight = $(this).children('img').height();
            //set w/h of hover effects based on image w/h
            $(this).children('a').css({
                width: imgWidth,
                height: imgHeight
            });
            $(this).children('._rollover').css({
                width: imgWidth,
                height: imgHeight
            });

           
        });


        /*image hovers - add addtional hover icon classes here*/
        $("._imageOriginal,._blogThumb,._videoOriginal").hover(

        function () {

            targetHover = $(this).parent().children('._rollover')
            $(targetHover).animate({
                "opacity": "0.9"
            }, hoverFadeSpeed);

            $(this).parent().children('._mediaIcon').animate({
                "opacity": "1"
            }, hoverFadeSpeed);

            //get reference width of image used
            widthRef = $(this).parent().children('._thumb').width();

            if ($(this).parent('.imageFrame')) {

                //hide the icon of the viewport
                $(this).css({
                    backgroundPosition: -widthRef
                });

                //position hover icon based on image width
                var iconPos = widthRef / 2 - hoverIconWidth / 2

                //animate the icon to the position
                $(this).stop().animate({
                    backgroundPosition: iconPos
                }, 200);

            }

        }, function () {

            targetHover = $(this).parent().children('._rollover')
            $(targetHover).animate({
                "opacity": "0"
            }, hoverFadeSpeed);

            $(this).parent().children('._mediaIcon').animate({
                "opacity": "0"
            }, hoverFadeSpeed);

            if ($(this).parent('.imageFrame')) {

                $(this).stop().animate({
                    backgroundPosition: -widthRef
                }, 200);

            }

        });


        //SOCIAL ------------------------------------------------------------------------------/
        $("._rolloverSocial").hover(

        function () {
            $(this).animate({
                "opacity": "1"
            }, hoverFadeSpeed);
        }, function () {
            $(this).animate({
                "opacity": "0"
            }, hoverFadeSpeed);
        });



        //init pajinate containers - add containers as necessary
        $('#blogContainer').pajinate({
            start_page: 0,
            items_per_page: 1,
            show_first_last: false,
            item_container_id: ".contentPaginate"
        }); //initialize pagination of blog items
        $('#portfolioContainer2').pajinate({
            start_page: 0,
            items_per_page: 1,
            show_first_last: false,
            item_container_id: ".contentPaginate"
        }); //initialize pagination of folio items
        
        //BLOG -------------------------------------------------------------------------------/
        $("#blogContainer .post").append('<div class="postClose"></div>');

        //read more click functions
        $(".readMore").click(function () {
            $(this).parent().parent().children(".postExcerpt").animate({
                opacity: 0
            }, {
                duration: pageFadeSpeed,
                complete: function () {

                    //enter the pose close button
                    $(this).parent().children(".postClose").show().animate({
                        opacity: 0.5
                    }, 200);

                    //hide the blog container as its not in use
                    $(this).hide();
                    $(this).parent().children(".postFull").css({
                        opacity: 0
                    });
                    //call our post content associated with the read more that was clicked
                    $(this).parent().children(".postFull").show().animate({
                        opacity: 1
                    }, {
                        duration: pageFadeSpeed
                    });

                }
            });
            return false;

        });


        //post close button functions
        $('.postClose').click(function () {
            var curPost = $(this).parent();

            //get the post thats open, slide it and hide it
            $(curPost).children('.postFull').animate({
                opacity: 0
            }, {
                duration: pageFadeSpeed,
                complete: function () {
                    $(this).hide();
                    //hide the close button														 
                    $(curPost).find('.postClose').stop().animate({
                        opacity: 0
                    }, 200, function () {

                        $(this).hide();

                    });

                    //re-enter the blog container
                    $(curPost).children('.postExcerpt').show().animate({
                        opacity: 1
                    }, {
                        duration: pageFadeSpeed
                    });


                }
            });

            return false;
        });

        //postClose:hover
        $('.postClose').hover(function () {

            $(this).css({
                opacity: 1
            });

        }, function () {

            $(this).css({
                opacity: 0.5
            });

        });


        //FORMS ------------------------------------------------------------------------------/
        /*- original code by Farid Hadi -http://www.faridhadi.com*/

        // hide form reload button
        $('#reload').hide();

        //field values on focus,on focus out
        $('#contactForm #name,#contactForm #email,#contactForm #subject,#contactForm #message').focus(function () {
            var initVal = $(this).val();
            $(this).val(initVal === this.defaultValue ? '' : initVal);
        }).blur(function () {
            var initVal = $(this).val();
            $(this).val(initVal.match(/^\s+$|^$/) ? this.defaultValue : initVal);
        });

        //submit click function
        $('#contactForm #submit').click(function () {

            // Fade in the prloader
            $('#contactForm #formProgress').hide();
            $('#contactForm #formProgress').html('Sending&hellip;');
            $('#contactForm #formProgress').fadeIn();

            // Disable the submit button
            $('#contactForm #submit').attr("disabled", "disabled");

            // Set temporary variables for the script
            var isFocus = 0;
            var isError = 0;

            // Get the data from the form
            var name = $('#contactForm #name').val();
            var email = $('#contactForm #email').val();
            var subject = $('#contactForm #subject').val();
            var message = $('#contactForm #message').val();


            //check if form element have verify class, if so remove and recheck
            if ($('#contactForm #name').hasClass('formVerify')) {
                $('#contactForm #name').removeClass('formVerify');
            }
            if ($('#contactForm #email').hasClass('formVerify')) {
                $('#contactForm #email').removeClass('formVerify');
            }
            if ($('#contactForm #message').hasClass('formVerify')) {
                $('#contactForm #message').removeClass('formVerify');
            }

            //Make sure bkgs are set to original
            $('#contactForm #name').addClass('formReset');
            $('#contactForm #email').addClass('formReset');
            $('#contactForm #message').addClass('formReset');

            // Validate the data
            if (name == 'Name*' || name == '') {
                $('#contactForm #name').addClass('formVerify');
                $('#contactForm #name').focus();
                isFocus = 1;
                isError = 1;
            }
            if (email == 'E-mail*' || email == '') {
                $('#contactForm #email').addClass('formVerify');
                if (isFocus == 0) {
                    $('#contactForm #email').focus();
                    isFocus = 1;
                }
                isError = 1;
            } else {
                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                if (reg.test(email) == false) {
                    $('#contactForm #email').addClass('formVerify');

                    if (isFocus == 0) {
                        $('#contactForm #email').focus();
                        isFocus = 1;
                    }
                    isError = 1;

                }
            }
            if (message == 'Message*' || message == '') {
                $('#contactForm #message').addClass('formVerify');
                if (isFocus == 0) {
                    $('#contactForm #message').focus();
                    isFocus = 1;
                }
                isError = 1;
            }

            // Terminate the script if an error is found
            if (isError == 1) {
                $('#contactForm #formProgress').html(formWarning);


                // Activate the submit button
                $('#contactForm #submit').removeAttr("disabled");

                return false;
            }

            $.ajaxSetup({
                cache: false
            });

            var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
            $.ajax({
                type: "POST",
                url: "php/submit-form.php",
                data: dataString,
                success: function (msg) {

                    // Check to see if the mail was successfully sent
                    if (msg == 'Mail sent') {

                        // Update the loader to a check + message
                        $('#sentConfirmMessage').html(formSuccess);

                        //Change the main title
                        $('#sentConfirmTitle').html(formSuccessTitle);

                        //Display the info
                        $('#sentConfirmMessage').fadeIn(1000);
                        $('#sentConfirmTitle').fadeIn(1000);

                        // Reinitialize the fields
                        $('#contactForm #name').val('Name*');
                        $('#contactForm #email').val('E-mail*');
                        $('#contactForm #subject').val('Subject');
                        $('#contactForm #message').val('Message*');

                        // Fade out the contact from, then toggle the height
                        $("#contactForm").animate({
                            "opacity": "0"
                        }, 1000);
                        $('#contactForm').delay(200).slideToggle("slow");

                        //Fade in reload link
                        $('#reload').fadeIn();


                        //Ensure new title is cufoned after sending
                        //Cufon.replace('h1#sentConfirmTitle');
                    } else {
                        $('#contactForm #formProgress').html(formError);
                    }

                    // Activate the submit button
                    $('#contactForm #submit').removeAttr("disabled");
                },
                error: function (ob, errStr) {
                    $('#contactForm #formProgress').html(formError);

                    // Activate the submit button
                    $('#contactForm #submit').removeAttr("disabled");
                }
            });

            return false;
        });

        // Contact form reload but function	
        $('#reload').click(function () {

            $("#contactForm").animate({
                "opacity": "1"
            }, 1000);
            $('#contactForm').animate({
                height: 'toggle'
            }, 1000);
            $('#sentConfirmMessage').html(formReload);
            $('#sentConfirmTitle').html(formReloadTitle);
            $('#reload').fadeOut();
            $('#contactForm #formProgress').html('*required');

    
        });
	
		$(".twitter").tweet({
        	join_text: "auto",
          	username: twitterAccount,
          	avatar_size: 40,
          	count: numTweets,
          	auto_join_text_default: "",
          	auto_join_text_ed: "I",
          	auto_join_text_ing: "I was",
          	auto_join_text_reply: "I replied",
         	auto_join_text_url: "I was checking out",
          	loading_text: "loading tweets..."
        });
        
    });
	
})(jQuery);
