﻿/*------------------------------------------------------------------------------
    JS Document (https://developer.mozilla.org/en/JavaScript)

    project:    Roxane
    created:    2012-01-03
    author:     Christophe ANDRIEU (http://www.stpo.fr)

    summary:    CONSTANTES
                UTILITIES
                WINDOW.ONLOAD
                ROLLOVER
                EMAIL
                GOOGLE_MAPS
                PLACEHOLDER
                FORM_CHECK
                KNOB
                HOME
----------------------------------------------------------------------------- */
/*  =CONSTANTES
----------------------------------------------------------------------------- */
jQuery.noConflict();
var d = document;
var w = window;
stpo = {};


/*  =UTILITIES
----------------------------------------------------------------------------- */
var log = function(x) {
    if (typeof console != 'undefined') {
        console.log(x);
    }
};


/*  =WINDOW.ONLOAD
----------------------------------------------------------------------------- */
jQuery(window).load(function(){

    // WARNING
    // Has to be attached to the window.load event
    // If not the @font-face rendering is sometimes not finished
    // And the calculated height could be wrong
    stpo.home();                    // Home collapse

});

jQuery(document).ready(function(){
    
    // Call Functions
    stpo.rollMe();                  // image rollover
    stpo.email();                   // email encode
    stpo.placeholder();             // placeholder for input
    stpo.formCheck();               // check da formz
    stpo.ggMaps();                  // Google Maps init
    stpo.knob();                    // Knob stuff
    
    if (jQuery.browser.msie && ((jQuery.browser.version == 6) || (jQuery.browser.version == 7))){
        // IE 6-7 FUNCTIONS ONLY
        
    }

    jQuery('#btn-new-message').click(function(){
        jQuery("#form-sender").removeClass('hide-sent').addClass('display-sent');
        jQuery("#sent").removeClass('display-sent').addClass('hide-sent');

        return false;
    });
});


/*  =ROLLOVER
----------------------------------------------------------------------------- */
stpo.rollMe = function() {
    
    jQuery('.rollMe').each(function(){
        
        var myImg = jQuery(this);
        
        // image preload
        var myRolledImg = document.createElement('img');
        myRolledImg.setAttribute("src", myImg[0].src.slice(0,-4) + '_hover' + myImg[0].src.substr(myImg[0].src.length - 4));
        
        // image rollover
        myImg.parent('a, button').hover(function(){
            
            myImg[0].src = myImg[0].src.slice(0,-4) + '_hover' + myImg[0].src.substr(myImg[0].src.length - 4); // tricky IE substr bug
            
        }, function(){
        
            myImg[0].src = myImg[0].src.split('_hover')[0] + myImg[0].src.split('_hover')[1];
            
        });
        
    });
        
}


/*  =EMAIL
----------------------------------------------------------------------------- */
stpo.email = function() {
    
    jQuery('.email').each(function(i){
        
        var myString = jQuery(this).html();
        
        var newString = myString.split('[AT]')[0] + '@' + myString.split('[AT]')[1].split('[DOT]')[0] + '.' + myString.split('[AT]')[1].split('[DOT]')[1];
        
        jQuery(this).html('<a href="mailto:' + newString + '">' + newString +'</a>');
        
    });

};


/*  =GOOGLE_MAPS
----------------------------------------------------------------------------- */
stpo.ggMaps = function(){
        
    // Déclaration des variables pour afficher la carte
    var map_;
    var Levallois = new google.maps.LatLng(48.8899164, 2.2867703);
    
    // Déclaration de l'icône personnalisée
    var monIconPerso = new google.maps.MarkerImage("/img/lg_roxane-ggmaps.png",
      // dimensions de l'image
      new google.maps.Size(40,40),
      // Origine de l'image 0,0.
      new google.maps.Point(0,0),
      // l'ancre (point d'accrochage sur la map) du picto (varie en fonction de ces dimensions)
      new google.maps.Point(0,34)
    );
    
    map_ = document.getElementById('map');
    
    // Déclaration des options de la map
    var options = {
      zoom: 14,
      center: Levallois,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    
    var map = new google.maps.Map(map_, options);
    
    // Création du marker
    var marker = new google.maps.Marker({
      position: Levallois,
      map: map,
      // Attribution de l'icône personnalisée à notre marker
      icon : monIconPerso,
      title: "The Roxane Company, Levallois-Perret, France"
    });
    
    // Infowindow on click on the marker
    google.maps.event.addListener(marker, 'click', function() {
        //window.location.href = 'http://g.co/maps/vagds';
        infowindow.open(map, marker);
    });
        
    var infowindow = new google.maps.InfoWindow({
        content: '<p style="color:#000; font-size: 12px; line-height: 1;"><strong>The Roxane Company</strong><br>39 rue Anatole France<br>92300 Levallois-Perret, FRANCE.</p><p style="font-size: 12px;"><a href="http://g.co/maps/vagds" style="color:#820e0c">Cette carte est trop petite, non&nbsp?</a></span></p>',
        maxWidth: '240'
    });

}
        
        
/*  =PLACEHOLDER
----------------------------------------------------------------------------- */
stpo.placeholder = function(){
    
    jQuery('input[type=text], input[type=search], input[type=password], input[type=email], textarea').each(function(i){
    
        var that = jQuery(this);
        
        // placeHold me!
        if (that.attr('value') == "") {
            that.val(that.attr('title'));
            that.addClass('placeholded');
        }
        
        // only for webkit
        that.bind('mouseup', function(e){
            e.preventDefault();
        });

        that.bind('focus', function(e){
            
            if (that.val() == that.attr('title')){
                 //that.select();
                 that.val('');
                 that.removeClass('placeholded');
            }
        });
        
        that.bind('blur', function(e){
            
            if (that.val() != that.attr('title')) that.removeClass('placeholded');
            else that.addClass('placeholded');
            
            // refill if empty
            if (!/[a-zA-Z0-9]/.test(that.val())) {
                that.val(that.attr('title'));
                that.addClass('placeholded');
            }
            
        });
    });
};


/*  =FORM_CHECK
----------------------------------------------------------------------------- */
stpo.formCheck = function(){
    
    // check value
    var checkField = function(that, event){

        var value = that.val(),
            title = that.attr('title'),
            type = that.attr('type'),
            parent = that.parent(),
            errorEmpty = false,
            errorFilled = false;

        // just required
        if (!/[a-zA-Z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöùúûüýÿ]/.test(value) || (value == title)) errorEmpty = true;

        // email
        else if (that.hasClass('requiredEmail')){

            if (!/^([a-z0-9][-a-z0-9_\+\.]*[a-z0-9])@([a-z0-9][-a-z0-9\.]*[a-z0-9]\.(arpa|root|aero|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|([0-9]{1,3}\.{3}[0-9]{1,3}))?$/.test(value)) errorFilled = true;

        }

        // radio
        else if ((type == 'radio') && (that.attr('checked')) && (value == '0')) errorEmpty = true;

        // display msg
        if (errorEmpty) parent.removeClass('errorFilled').addClass('error errorEmpty');
        else if (errorFilled) parent.removeClass('errorEmpty').addClass('error errorFilled');
        else parent.removeClass('error errorEmpty errorFilled');

        if (errorEmpty || errorFilled) return false;
        else return true;
    }

    jQuery('#form-sender').bind('submit', function(e){

        var globalError = false;

        jQuery(this).find('.required:visible').each(function(){

            var that = jQuery(this);

            if (!checkField(that, e)) globalError = true;

        });

        //return (!globalError);

        if (!globalError){
            var email	 	= jQuery("#email").val();
            var message 	= jQuery('#message').val();
            var emailValue = jQuery("#email").attr('title');
            var messageValue = jQuery("#message").attr('title');
            var dataString 	= 'email=' + email + '&message=' + message;

            jQuery.ajax({
                type: 'POST',
                url: '/inc/process_send_message.php',
                data: dataString,
                success: function(result) {
                    jQuery("#email").attr('value', emailValue);
                    jQuery("#message").attr('value', messageValue);

                    jQuery("#form-sender").removeClass('display-sent').addClass('hide-sent');
                    jQuery("#sent").removeClass('hide-sent').addClass('display-sent');
                }
            });

            return false;
        }else{
            return (!globalError);
        }
    });
}


/*  =KNOB
----------------------------------------------------------------------------- */
stpo.knob = function() {
    
    if (document.getElementById('knob')) {
    
        // cache
        var myKnob = jQuery('#knob'),
            mySwitch = jQuery('#switch a'),
            myHash = window.location.hash.split('#')[1];
        
        // isotope load/behave
        var goIsotope = function(daFilter){
            
            jQuery('#isotope-list').isotope({
                // options
                filter: daFilter,
                itemSelector : '.isotope-item',
                masonry: {
                    columnWidth: 156 // don't ask
                }
            });
            
        };
        
        
        // initial position / list
        if ((myHash == undefined) || (myHash == '') || (myHash == 'case-study')) var initialRank = jQuery('#sort-by').find('a:first-child').parent().attr('class').split('step-')[1];
        else var initialRank = jQuery('#sort-by').find('a[href=#'+ myHash +']').parent().attr('class').split('step-')[1];
        
        // initial position / knob
        jQuery('#sort-by .step-' + initialRank + ' a').addClass('arrow-2');
        myKnob.addClass('pos-' + initialRank);
        
        // initial position / switch
        if (myHash == 'case-study') mySwitch.addClass('on');
        
        // initial position / filter
        if ((myHash == 'tous') || (myHash == 'all') || (myHash == undefined)) var myFilter = '*';
        else myFilter = '.' + myHash;
        
        goIsotope(myFilter);    
        
        
        // nav behave
        jQuery('#knob-nav li a').each(function(i){
            
            var that = jQuery(this),
                rank = that.parent().attr('class').split('step-')[1];
            
            // rollover    
            that.hover(function(){
                
                myKnob[0].className = 'pos-' + rank;
                
            }, function(){
                
                myKnob[0].className = 'pos-' + initialRank;
                
            });
            
            // click
            that.bind('click', function(){
                
                // don't proceed if already selected
                if ( that.hasClass('arrow-2') ) { return; }
                
                // knob
                jQuery('#knob-nav').find('.arrow-2').removeClass('arrow-2');
                that.addClass('arrow-2');
                initialRank = rank;
                myKnob[0].className = 'pos-' + initialRank;
                
                // isotope sort
                var myFilter = '.' + jQuery(this).attr('href').slice(1);
                if ((myFilter == '.tous') || (myFilter == '.all')) myFilter = '*';

                if (mySwitch.hasClass('on')) myFilter += '.case-study';
                
                goIsotope(myFilter);
                
                that.blur();
                
            });
            
        });
        
        
        // knob behave
        myKnob.bind('click', function(){
            
            var newItem = jQuery('#knob-nav').find('.arrow-2').parent().next().find('a');
            if (newItem.length == '0') newItem = jQuery('#knob-nav li:first-child a');
            newItem.click();
            
        });
        
        
        // switch behave
        mySwitch.bind('click', function(){
            
            var that = jQuery(this),
                selected = jQuery('#knob-nav').find('.arrow-2').attr('href').slice(1);
            
            that.toggleClass('on');
            
            if (that.hasClass('on')) var myFilter = '.' + jQuery(this).attr('href').slice(1);
            else var myFilter = '';
            
            if ((selected != 'tous') && (selected != 'all')) myFilter += '.' + selected;
            
            goIsotope(myFilter);        
            
            that.blur();
            return false;
            
        });
        
    }

};


/*  =HOME
----------------------------------------------------------------------------- */
stpo.home = function() {

    jQuery('#home-collapse').slideDown();

    jQuery('#home-collapse .home-item').each(function(i){
        
        // init
        var that = jQuery(this),
            myTellMeMore = that.find('.tell-me-more'),
            myHeight = myTellMeMore.height(),
            myMore = that.find('.more'),
            myCaller = that.find('.arrow-1, .caller'),
            myLinkCaller = that.find('.arrow-1'),
            myMinus = that.find('.minus');
        
        myTellMeMore.addClass('closed');
        var myClosedHeight = myTellMeMore.height();
        myMore.hide();
        
        // behave
        myCaller.bind('click', function(){
            
            if (!that.hasClass('open-panel')){
            
                // the others
                var othersOpen = jQuery('.open-panel');
                othersOpen.find('.tell-me-more').animate({
                    height: myClosedHeight
                }, 500, function(){
                    othersOpen.removeClass('open-panel');
                    othersOpen.find('.more').fadeOut('fast', function(){
                        othersOpen.find('.arrow-1').fadeIn('fast');
                    })
                });
                
                // this one
                that.addClass('open-panel');
                
                myTellMeMore.animate({
                    height: myHeight
                }, 500, function(){
                    
                    myLinkCaller.fadeOut('fast', function(){
                        myMore.fadeIn('fast');
                    });
                    
                });
                
            }
                
            myCaller.blur();
            return false;
            
        });
        
        // minus
        myMinus.bind('click', function(){
            
            myTellMeMore.animate({
                
                height: myClosedHeight
                
            }, 500, function(){
                that.removeClass('open-panel');
                myMore.fadeOut('fast', function(){
                    myLinkCaller.fadeIn('fast');
                });
                
            });
            
            myMinus.blur();
            return false;
            
        });        
        
    });

};
