//GA
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-848766-50']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

//Scripts
$(document).ready(function() {

    //Commons
    $('.colorbox').colorbox({
        opacity: 0.5
    });

    //Single functions
    //HOME page
    if ($.isPage('') || $.isPage('index.php')) {
        slider(1, 'h', '.home-slider', 800);
    }

    //STUFE landing-page
    if ($.isPage('stufe.php')) {

        slider(4, 'h', '.stufe-slider', 300);

        $GF.fn.slides({
            menu: '#contributes-menu',
            slider: '#contributes-list',
            width: 1000,
            applyClass: 'parent'
        });
    }
	
	
	 if ($.isPage('azienda.php')) {
	
			$GF.swfWrite(
		{
			swf : {
				movie 	: 'spot-tv.swf',
				wrapper : 'spot-tv',
				width	: 620,
				height	: 350
			}
		});
	
	}
	
    //PRODUCT page
    if ($('#selector').length) {

        changeProduct();

        slider(2, 'v', '#gallery-slider', 300);

        $('a[rel=gallery]').colorbox({
            opacity: 0.5
        });

        $("#related a").each(function() {
            var content = $(this).attr('rel');
            $(this).simpletip({
                fixed: false,
                content: content
            });
        });

    }

    if ($.isPage('rivestimenti.php')) {

        selectTexture();

    }

    if ($.isPage('rivenditori.php')) {

       $GF( '#frm-rivenditori' ).validate();	
		
		$("#regions").change(function(){						  
			
			var region = $( this ).find( ':selected' ).attr( 'name' );
			//alert(region)
			
				$('#provinces').load('/assets/ajax/province.php #'+region, function(){
					$('#provinces').show(500, function(){
						$('#provinces').change(function(){
							$('#send-request').show(500);
						})
					});
				});
		});
		
		
		
		//gotoThis();
        //toTop();

    }

    if ($.isPage('contatti.php')) {

        gmap();
        $GF( '#frm-contatti' ).validate();	
		//Show form
		$('#gphone').fadeIn(0);

    }

})

/*-------------------- FUNCTIONS ---------------------------*/

// @info 	Check current pag
// @usage	if($.isPage('pageName'))
jQuery.isPage = function(checkFor) {

    var url = window.location.pathname;
    var page = url.split('/');
    page.reverse();

    if (checkFor == page[0]) {

        return true;
    } else {
        return false;
    }
}

// @info 	
// @usage	slider(offset, container)
function slider(offset, style, container, speed) {

    //Custom vars
    var offset = offset;
    var $container = $(container);
    var timer = null;
    var timeout = 3000;

    //Global vars
    var $buttons = $('.stop');
    var $next = $container.find('.next').children('a');
    var $prev = $container.find('.prev').children('a');
    var i = 0;
    var pos = 0;
    var activity = true;

    //Build ul
    var $slider = $container.find('ul');
    var numbli = $slider.find('li').length;
    var liwidth = $slider.find('li').width();
    var liheight = $slider.find('li').height();
    var lisize = null;
    var ulsize = null;

    if (style == 'h') {
        
		//Set ul size
        lisize = liwidth;
        ulsize = numbli * lisize;
        //Set ul height/width 
        $slider.css({ width: ulsize });


    } else {
 
		lisize = liheight;
        ulsize = numbli * lisize;
        $slider.css({ height: ulsize });
       
    }
	
	function animate( margin) {
		
		var options = {};
		
		if( style == 'h' ){
			options = { marginLeft : margin };
		}
		else {
			options = { marginTop: margin };
		}
		
		$slider.stop().animate( options, speed );
		
    }
	

    //Set timer
    setTimeout(function() {

        var effect = function() {

            i++;

            if (i <= numbli - offset) {

                pos = -lisize * i;
				
				animate( pos );

                } else {

                i = 0;
                pos = 0;

                animate( pos );
				
                }

            //start Timer
            timer = setTimeout(effect, timeout);

        };

        //start Timer
        timer = setTimeout(effect, timeout);

        //If out set Timer
        $buttons.hover(function() {

            //Clear
            clearTimeout(timer);

        }, function() {

            //Set Interval
            timer = setTimeout(effect, timeout);

        })

        //Animate slider
        $next.click(function() {

            clearTimeout(timer);

            i++;

            if (i <= numbli - offset) {

                pos = -lisize * i;

                animate( pos );

                } else {

                i = 0;
                pos = 0;

               animate( pos );
				
                }
            return false;

        });

        $prev.click(function() {

            clearTimeout(timer);

            if (0 < i && i <= numbli - offset) {

                i--;

                pos = -lisize * i;

                animate( pos );

                }
            return false;
        });

    })
    }

//Select product
function changeProduct() {

    //Change
    function jumptoProduct(targ, selObj, restore) {
        eval(targ + ".location='" + selObj.options[selObj.selectedIndex].value + "'");
        if (restore)
            selObj.selectedIndex = 0;
    }

    $('select').change(function() {
        jumptoProduct('parent', this, 0);
    })
    }

function gotoThis() {

    function move(id) {

        $('html,body').animate({
            scrollTop: $(id).offset().top
        }, 800);

    }

    $('option').click(function() {

        tothis = $(this).attr('value');
        move(tothis);

        return false;
    })

    }

function toTop() {

    $('.up').click(function() {

        $('html,body').animate({
            scrollTop: 0
        }, 800);

        return false;

    })

    }

//Select cat
function selectTexture() {

    var $texture = $('.rivestimenti a');

    $texture.hover(function() {

        var $this = $(this);
        var img = $this.children('img').attr('src');
        var cat = $this.attr('rel');
        var name = $this.attr('title');

        $('#gallery img').attr('src', img);
        $('#selector h1').html(name);
        $('#selector h5').html(cat);

    }, function() {
        //
        })
    }

//Show products description
function showProdDesc() {

    var $button = $('.details a');

    $button.click(function() {

        var $this = $(this);

        if ($this.hasClass('selected')) {

            $this.removeClass('selected')
                $this.parent().next('.description').slideUp();

        } else {

            $this.parent().next('.description').slideDown();
            $this.addClass('selected')

            }

        return false;

    })

    }

function gmap() {

	$GF( '#map' ).googlemap(
		{
			markers : [
				{
					 coord: '45.698177,9.759293',
					 title: 'La Stufa Bergamasca',
					 image: '/assets/style/img/commons/tip-map.png'
				}
			],
			type: 'hybrid',
			zoom: 14
		});
}

//Validate form
function validateForm() {

    $('#contact-form').submit(function() {

        var name = $("input[name=name]").val();
        var company = $("input[name=company]").val();
        var tel = $("input[name=tel]").val();
        var email = $("input[name=email]").val();

        var error = false;
        var at = email.indexOf("@");
        var dot = email.indexOf(".");

        if (role == "") {
            error = true;
            $("input[name=company]").val("Campo necessario");
        }
        if (name == "") {
            error = true;
            $("input[name=name]").val("Campo necessario");
        }
        if (tel == "") {
            error = true;
            $("input[name=tel]").val("Campo necessario");
        }

        if ((email == "") || (at == -1) || (dot == -1)) {
            error = true;
            $("input[name=email]").val("Campo non valido");
        }

        if (error) {
            $('input[name=send]').animate({
                marginLeft: "3px"
            }, 200).animate({
                marginLeft: "-3px"
            }, 200).animate({
                marginLeft: "3px"
            }, 200).animate({
                marginLeft: "0"
            }, 200);
        } else {

            $.ajax({
                cache: true,
                type: 'post',
                url: '/assets/form-mail/contacts.php/',
                data: $(this).serialize(),
                success: function(data) {
                    alert('ok')
                    }
            });
        }
        return false;
    });
}
