/*
 * Web-site developed with PHP 5
 *
 * Copyright (c) 2011 MagicBrain
 * http://www.magicbrain.pt
 *
 * Licensed under GPLv3
 * http://www.gnu.org/licenses/
 *
 * ----------------------------------------------------------------------
 * This file is part of index.php.
 *
 * index.php is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * index.php is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with index.php.  If not, see <http://www.gnu.org/licenses/>.
 * ----------------------------------------------------------------------
 *
 * Launch  : January 2012
 * Version : 4-stable
 * Released: Friday 13th January, 2012 - 13:11
 *
 */



/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * ------------------------------------------------------------------------------- */
(function($) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
})(jQuery);



/**
 * INITIALIZE VARIABLES
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
var triggerClick = '';



/**
 * ANIMATE NEW CONTACTS INFORMATION
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
function animateNewContacts()
{
    $('#newContacts').animate({
        "opacity" : 0.3
    }, 1000, function() {
        $('#newContacts').animate({
            "opacity" : 1
        }, 1000, function() {
            animateNewContacts();   
        });
    });
}



/**
 * GOOGLE MAPS GLOBAL SCOPE VARIABLE FOR API v3.0 INTERACTION
 * ------------------------------------------------------------------------------------ */
var global = {};
global.initMap = function(){
    $.post("components/inc/ajax/get_googleMaps.php", { "id": 1 }, function(data)
    {
        $("#gmaps").gMap(
        {
            controls: {
                panControl         : true,
                zoomControl        : true,
                mapTypeControl     : false,
                scaleControl       : false,
                streetViewControl  : false,
                overviewMapControl : false
            },
            scrollwheel: true, //data.scrollwheel,
            maptype: 'ROADMAP',
            markers: [
                {
                    latitude: 40.212375, //data.latitude,
                    longitude: -8.426773, //data.longitude,
                    html: "MagicBrain | OFPG, Lda.<br>Rua Saragoça, 18", //data.html,
                    icon: {
                        image: "http://www.google.com/mapfiles/marker.png",
                        shadow: "http://www.google.com/mapfiles/shadow50.png",
                        iconsize: [20, 34],
                        shadowsize: [37, 34],
                        iconanchor: [9, 34],
                        shadowanchor: [19, 34]
                    }
                }
            ],
            zoom: 16
        });
        $("#gmaps").removeClass('ajaxFirstLoad');
    }, "json");
}



/**
 * STARTUP
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
$(function(){


    /**
     * Enter the website or skip the intro
     * (c) Salustiano Silva [MagicBrain | OFPG, Lda.] [salustiano.silva@magicbrain.pt]
     * ------------------------------------------------------------------------------- */
    var cookieOptions = { expires: 7, path: '/' };

    if ($.cookie('mb_intro')!=null && $('#loading').size()==1)
    {
        $('#loading').remove();
    }
    else
    {
        $('.enterWebsite').bind("click", function(e) {

            e.preventDefault();

            var cookieValue = $(this).html();
            $.cookie('mb_intro', cookieValue, cookieOptions);

            $('#loading').fadeOut('fast', function() {
                $('#loading').remove();
            });

        });
    }
    
    $('#viewIntro').bind("click", function(e) {
        e.preventDefault();
        $.cookie('mb_intro', null, cookieOptions);
        location.replace( location.href.replace(/\?.*$/, '') + '?' + Math.random() );
    });



    $('#getIpAddress').bind("mouseenter", function() {
        $(this).find('h6').fadeIn();
    });
    $('#getIpAddress').bind("mouseleave", function() {
        $(this).find('h6').fadeOut();
    });


    /**
     * Dynamic Height for main Containers
     * (c) Salustiano Silva [MagicBrain | OFPG, Lda.] [salustiano.silva@magicbrain.pt]
     * ------------------------------------------------------------------------------- */
    $('.module').css({
        "height" : $(window).height() - $('.hd').outerHeight(),
        "margin" : "0 0 " + $('.ft').outerHeight() + "px 0"
    });
    $('#mb_logo').css({
        "left" : $('.module').position().left
    });
    // reset the view in case of refresh!
    $('html, body').animate({scrollTop: '0'}, 0);


    /**
     * Homepage Mini Slider
     * (c) Salustiano Silva [MagicBrain | OFPG, Lda.] [salustiano.silva@magicbrain.pt]
     * ------------------------------------------------------------------------------- */
    function highlight_toggle()
    {
        $("#highlightsWrap .images img").first().appendTo('#highlightsWrap .images').fadeOut(3000);
        $("#highlightsWrap .images img").first().fadeIn(3000);
    
        setTimeout(highlight_toggle, 5000);
    }
    highlight_toggle();
    

    /**
     * ANIMATE NEW CONTACTS INFORMATION
     */
    animateNewContacts();

     
    /* BACK TO TOP */
    if ($('#back-top').size()==1)
    {
        $('#back-top').click(function(event) {
            event.preventDefault();
            $('html, body').animate({scrollTop: '0'}, 1000);
            $('.switchModule').removeClass('active');
        });
    }



    /**
     * Switch Module
     * (c) Salustiano Silva [MagicBrain | OFPG, Lda.] [salustiano.silva@magicbrain.pt]
     * ------------------------------------------------------------------------------- */
    if ($('.switchModule').size()>=1)
    {
        $('.switchModule').bind("click", function(event)
        {
            event.preventDefault();

            $('.switchModule').closest('li').removeClass('active');

            if ($(this).attr("href").indexOf("contacts") !== -1)
            {
                if ($('#gmaps.ajaxFirstLoad').size()==1)
                {
                    $.getScript('http://maps.google.com/maps/api/js?sensor=false&callback=global.initMap', function(data, textStatus) {
                        console.log(textStatus);
                    });
                }
            }

            $(this).closest('li').addClass('active');

            var t = $(this).attr("href"),
                x = $(t).position();

            $('html, body').animate({
                scrollTop : x.top - $('.hd').outerHeight()
            }, 1000);
        });
    }


    /**
     * Toggle Page :: ABOUT Texts
     * (c) Salustiano Silva [MagicBrain | OFPG, Lda.] [salustiano.silva@magicbrain.pt]
     * ------------------------------------------------------------------------------- */
    if ($('.subMenuSwitch').size()>=1)
    {
        $('.subMenuSwitch').bind("click", function(event) {
            event.preventDefault();
            
            if (!$(this).closest('li').hasClass('active'))
            {
                // get the target id string
                var type = $(this).attr("href").replace("#", '');

                // hide the active class from the menu list element
                $(this).closest('.module').find('.menuListBg .active').removeClass('active');
                
                // add the active class to the clicked menu element
                $(this).addClass('active');

                // find target elements
                if ($('html').hasClass('touch'))
                {
                    var $targetContent = $(this).closest('.module').find('.subMenuTarget:first-child .scroller');
                }
                else
                {
                    var $targetContent = $(this).closest('.module').find('.subMenuTarget:first-child .content');
                }
                var $targetTitle   = $(this).closest('.module').find('.subMenuTarget:first-child > h2:first-child');
                
                // check for touch device
                var deviceType = ($('html').hasClass('touch')) ? 'touch' : 'no-touch';

                $.post("components/inc/ajax/get_siteTxts.php", { "type": type }, function(data)
                {
                    // place the html and title into the current visible target older
                    $targetContent.html(data.subtitle + data.content).text();
                    $targetContent.find('p:first-child').addClass('color3 shadow');
                    $targetTitle.html(data.title).text();

                    // reload the scroll bars to update the content size
                    if (deviceType == 'touch')
                    {
                        myScroll.refresh();
                    }
                    else
                    {
                        mCustomScrollbars();
                    }

                }, "json");
            }
        });
    }


    /**
     * Campaign Posters Zoom
     * (c) Salustiano Silva [MagicBrain | OFPG, Lda.] [salustiano.silva@magicbrain.pt]
     * ------------------------------------------------------------------------------- */
    $(".posterZoom").live('click', function(event) {

        var largeImg = $(this).find('.hidden').html(),
            $loader   = $(this).find('.loader');
            
        $loader.removeClass('hidden');

        // Insert preloaded image after it finishes loading
        $('<img>')
        .attr('src', largeImg)
        .load(function(){
            $('body').append('<div class="zoomMe"><img src="'+largeImg+'"><div class="close"> </div></div>');
            $(".zoomMe").css({
                "top" : $('#campaign_images').position().top + $('#page_header').height()
            });
            $loader.addClass('hidden');
            $(".zoomMe").slideFadeToggle(function() {
                $(this).find('img').css({
                    "margin-top" : (($(window).height() - $(this).find('img').height())/2) + "px"
                });
                $(this).find('.close').css({
                    "right" : ((($(window).width() - $(this).find('img').width())/2)-50) + "px"
                });
            });
        });

        return false;

    });

    $(".close").live('click', function() {
        $(".zoomMe").slideFadeToggle(function() { 
            $(".zoomMe").remove();
        });
        return false;
    });


    /**
     * Open Links in new Window
     * (c) http://prandall.com/
     * ------------------------------------------------------------------------------- */
    $('a[rel="openNewWindow"]')
    .click( function() {
        window.open( $(this).attr('href') );
        return false;
    });

});


$.fn.slideFadeToggle = function(easing, callback) {
    return this.animate({ opacity: 'toggle', height: 'toggle' }, "fast", easing, callback);
};



/**
 * CUSTOM SCROLL BARS --FOR TOUCH DEVICES--
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
if ($('html').hasClass('touch'))
{
    var myScroll;
    function loaded(id) {
        myScroll = new iScroll(id, { scrollbarClass: "myScrollbar" });
    }

    document.addEventListener("touchmove", function (e) { e.preventDefault(); }, false);
    document.addEventListener("DOMContentLoaded", loaded("mod_about_intro"), false);
    document.addEventListener("DOMContentLoaded", loaded("mod_services_intro"), false);
}



/**
 * CUSTOM SCROLL BARS --FOR NON TOUCH DEVICES--
 * ---------------------------------------------------------------------------------------------------------------------------------------- */
if ($('html').hasClass('no-touch'))
{
    function mCustomScrollbars()
    {
        $("#mod_services_intro").mCustomScrollbar("vertical",400,"easeOutCirc",1.05,"auto","yes","yes",10);
        $("#mod_about_intro").mCustomScrollbar("vertical",400,"easeOutCirc",1.05,"auto","yes","yes",10);
    }
    mCustomScrollbars();
}



/**
 * TOUTCH EVENTS
 * ------------------------------------------------------------------------------- */
//Assign handlers to the simple direction handlers.
var swipeOptions=
{
    click:click,
    swipe:swipe,
    threshold:50
}

$(function()
{           
    //Enable swiping...
    // $(".switchModule").swipe( swipeOptions );
    
    //Assign a click handler to a child of the touchSwipe object
    //This will require the jquery.ui.ipad.js to be picked up correctly.
    //$(".switchModule").click( countBlueClicks );
});

function click(event, target)
{
    // NEED TO VERIFY SINCE ITS SENDING THE CLICK EVENT TWICE ON NON-TOUTCH DEVICES
    // $(this).trigger("click");
}

function swipe(event)
{
    // alert('Swipe');
}

