﻿// Simple log
var log = function (msg) {
    if (!$('.log').size()) {
        $('<div class="log" />').appendTo('.page');
    }
    $('.log').append(msg.replace(/^([^:]*):(.*)$/, '<p><b>$1:</b> <span class="$1">$2</span></p>'))
                    .attr({ scrollTop: $('.log').attr('scrollHeight') })
                    .find('p:nth-child(even)').addClass('even');
};

function loadAddress() {
  
    var title = document.title;
    var track = function () {
        log('track: ' + arguments[0]);
    };

    // Serialization utility
    var serialize = function (obj, re) {
        var result = [];
        $.each(obj, function (i, val) {
            if ((re && re.test(i)) || !re)
                result.push(i + ': ' + (typeof val == 'object' ? val.join
                            ? '\'' + val.join(', ') + '\'' : serialize(val) : '\'' + val + '\''));
        });
        return '{' + result.join(', ') + '}';
    };

    // Init and change handlers
    $.address.init(function (event) {
    	$.address.crawlable(true);
		$.address.value('/homepage?oper=showarea');
      
        /*log('init: ' + serialize({
        value: $.address.value(),
        path: $.address.path(),
        pathNames: $.address.pathNames(),
        parameterNames: $.address.parameterNames(),
        queryString: $.address.queryString()        
        }));*/	
    }).change(function (event) { 
        /*log('change: ' + serialize(event, /parameters|parametersNames|path|pathNames|queryString|value/));*/
        /*log(readCookie('site_lang'));*/

        var names = $.map(event.pathNames, function (n) {
            return n.substr(0, 1).toUpperCase() + n.substr(1);
        }).concat(event.parameters.id ? event.parameters.id.split('.') : []);
        var links = names.slice();
	
				
        _id = $.address.parameter('id');
        _oper = $.address.parameter('oper');
        
        if (_oper=="showtools" || _oper=="dirlink") {
        	loadtool(_id);
            $.address.title("Affri System - " + links[links.length - 2]);
    	}
    	
    	if (_oper=="showarea") {
        	loadMainMenu($.address.pathNames());
            $.address.title("Affri System - " + links[links.length - 2]);
    	}
    	    	
    	if (_oper=="showpromo") {
        	loadpromo(_id);
    	}
   	});
}
function goHome() {
	window.location = "http://www.affri.com/index.asp";
}


function loadregister_form() {
    $("#content").load("registrazione-affri.asp");
}

function loadcontact_form() {
    $("#content").load("contatti-affri.asp");
}

function loadpromo(idPromo) {
    $("#content").load("promo.asp?id=" + idPromo);
}

function loadofferta(idTool) {
    $("#content").load("listinoofferta.asp?id=" + idTool);
}


siteUrls = { "homepage": "homepage.asp",
             "eventi": "events.asp",
             "azienda": "factory.asp",
             "rivenditori": "resellers.asp",
             "contatti": "contacts.asp",
             "dovesiamo": "location.asp",
             "offerte": "offers.asp",
             "download": "download.asp"}

function loadMainMenu(page) {
	
    if (page!="") {
        $("#content").load(siteUrls[page]);
        return true;
    }
  
    return true;
}

function loadmacro(idMacro) {
    //alert('load_macro' + idMacro);
    $("#content").load("macro.asp?id=" + idMacro);
}

function loadtool(idTool) {
    $("#content").load("strumento.asp?id=" + idTool);    
}

function show_event() {
	$("#content").load("event.asp");
}

function download_pdf(pdf) {
    alert(pdf);
}

var timer;
function slideShow(speed) {
    clearInterval(timer);

	//append a LI item to the UL list for displaying caption
	$('ul.slideshow').append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3><p></p></div></li>');

	//Set the opacity of all images to 0
	$('ul.slideshow li').css({opacity: 0.0});
	
	//Get the first image and display it (set it to full opacity)
	$('ul.slideshow li:first').css({opacity: 1.0});
	
	//Get the caption of the first image from REL attribute and display it
	$('#slideshow-caption h3').html($('ul.slideshow a:first').find('img').attr('title'));
	$('#slideshow-caption p').html($('ul.slideshow a:first').find('img').attr('alt'));
		
	//Display the caption
	$('#slideshow-caption').css({opacity: 0.4, bottom:0});
	
	//Call the gallery function to run the slideshow	
	timer = setInterval('gallery()', speed);
	
	//pause the slideshow on mouse over
	$('ul.slideshow').hover(
		function () {
			clearInterval(timer);	
		}, 	
		function () {
			timer = setInterval('gallery()',speed);			
		}
	);
	
}

function gallery() {

	//if no IMGs have the show class, grab the first image
	var current = ($('ul.slideshow li.show') ?  $('ul.slideshow li.show') : $('#ul.slideshow li:first'));
		
	//Get next image, if it reached the end of the slideshow, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption') ? $('ul.slideshow li:first') : current.next()) : $('ul.slideshow li:first'));

	//Get next image caption
	var title = next.find('img').attr('title');
	var desc = next.find('img').attr('alt');

	//Set the fade in effect for the next image, show class has higher z-index
	next.css({ opacity: 0.0 }).addClass('show').animate({ opacity: 1.0 }, 1000);

	//Hide the caption first, and then set and display the caption
	$('#slideshow-caption').slideToggle(0, function () {
	    $('#slideshow-caption h3').html(title);
	    $('#slideshow-caption p').html(desc);
	    $('#slideshow-caption').slideToggle(0);
	});
	
	//Hide the current image
    current.animate({ opacity: 0.0 }, 1000).removeClass('show');
}


function init_objects() {
	$(document).ready(function() {	
	
		scroller(3500);
		//slideShow(7000);		

		$("#chained").scrollable({circular: true, mousewheel: true}).navigator().autoscroll({ interval: 7000 });
	});
}

var showTime;
var scrollTime = 50;
var scrollStep = 2;
var headline_interval;
var cont_hover = false;

function scroller(timeout) {
	
	showTime = timeout;
	
	current_headline = 0;
    old_headline = 0;
    headline_count = $("div.contentgrp").size();

    var vis_area = parseInt($('#scrollup').css('height'));
    for (i = 0; i < headline_count; i++)
        $('div.contentgrp').eq(i).css('top', vis_area + 'px');

    if (headline_interval != 0) {
        clearInterval(headline_interval);
        headline_interval = 0;
    }

    setTimeout(headline_rotate, showTime);

    $('div.contentgrp').eq(current_headline).css('top', '5px');

    $('#scrollup').hover(function () {
        if (headline_interval != 0) {
            clearInterval(headline_interval);
            headline_interval = 0;
        }
        cont_hover = true;
    }, function () {
        setTimeout(headline_rotate, 200);
        cont_hover = false;
    });
}
function headline_rotate() {

    if (cont_hover)
        return;

    if (headline_interval == 0) {
        current_headline = (old_headline + 1) % headline_count;
        headline_interval = setInterval(headline_rotate, scrollTime);
    }

    var topOld = parseInt($('div.contentgrp').eq(old_headline).css('top'));
    topOld -= scrollStep;
    $('div.contentgrp').eq(old_headline).css('top', topOld + 'px');

    var topNew = parseInt($('div.contentgrp').eq(current_headline).css('top'));
    topNew -= scrollStep;
    $('div.contentgrp').eq(current_headline).css('top', topNew + 'px');

    if (topNew < 3) {
        clearInterval(headline_interval);
        headline_interval = 0;

        $('div.contentgrp').eq(old_headline).css('top', $('#scrollup').height() + 5 + 'px');
        old_headline = current_headline;

        if (!cont_hover)
            setTimeout(headline_rotate, showTime);
    }
}

function search_tool() {
	if ($('#search_string').val() != '') {
		$("#content").load("search.asp?str="+$('#search_string').val());
	}
}

function echeck(str) {
    var at = "@";
    var dot = ".";
    var lat = str.indexOf(at);
    var lstr = str.length;
    var ldot = str.indexOf(dot);
    var msg = "L'indirizzo email che hai inserito non è valido.";

    if ((str.indexOf(at) == -1) ||
        (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) ||
        (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) ||
        (str.indexOf(at, (lat + 1)) != -1) ||
        (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) ||
        (str.indexOf(dot, (lat + 2)) == -1) ||
         (str.indexOf(" ") != -1) )
    {
        alert(msg);
        return false
    }

    return true
}

function change_to_ita() {
    createCookie('site_lang', '1', 365);
   window.location.reload(false);
}

function change_to_eng() {
    createCookie('site_lang', '2', 365);
    window.location.reload(false);
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = '; expires=' + date.toGMTString();
    }
    else expires = '';
    document.cookie = name + '=' + value + expires + '; path=/';
}

function readCookie(name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
} 
