/**
 * Lbreria per la gestione delle chiamate al server
 *
 * @author Gianfranco Castro <gianfranco.castro@nurun.com>
 * @since 2010 July 27
 * @see jquery-1.4.2.js, jquery.cookie.js
 */


/**
 * Configurazione iniziale
 */

// === Pagine di uscita verso il visualizzatore del compare
var outComparePage = new Array();
outComparePage['CAR']          = 'compare.html';     
outComparePage['MOTORCYCLE']   = 'compare.html';
outComparePage['TRUCK-BUS']    = 'compare.html';

// === Pagina che effettua la chiamata al server
var serverCall = new Array();
serverCall['CAR']			     = '/templates/pirellityre/pages/car-compare-item.jsp';
serverCall['MOTORCYCLE']		 = '/templates/pirellityre/pages/motorcycle-compare-item.jsp';
serverCall['TRUCK-BUS']			 = '/templates/pirellityre/pages/truck-bus-compare-item.jsp';


// --------------------------------------------------------------------
// --------------------------------------------------------------------
// --------------------------------------------------------------------

/**
 * Crea un COOKIE che rappresenta la sessione corrente
 */
function Nurun_CreateSession()
{
    // === Se non ho nessuna sessione, allora la creo
    if($.cookie('PIRELLINURSESSION')==null || $.cookie('PIRELLINURSESSION')=='')
    {
        var d = new Date();
        var newSession = d.getTime()+'NURUN'+__randomChars(8, false);
        $.cookie('PIRELLINURSESSION', newSession, {path: '/', expires: 30});
    }
}


/**
 * Crea un COOKIE che rappresenta la sessione corrente per
 * un determinato tipo di compare
 * @param type = (CAR|MOTORCYCLE|TRUCK)
 */
function Nurun_CreateCompareSession(type)
{
    if(type=='') return;
    if($.cookie('PIRELLINURSESSION')=='') Nunun_CreateSession();

    if($.cookie('PIRELLINURSESSION'+'_'+type)==null || $.cookie('PIRELLINURSESSION'+'_'+type)=='')
    {
        var d = new Date();
        var newSession = d.getTime()+'NURUN'+__randomChars(8, false) + "@";
        $.cookie('PIRELLINURSESSION'+'_'+type, newSession, {path: '/', expires: 30});
    }
}


/**
 * Resitituisce quanti prodotti ci sono nel carrello
 *
 * @public
 * @param type = (CAR|MOTORCYCLE|TRUCK)
 */
function Nurun_getCompareItems(type)
{
    // var base = 'add to compare <strong>(0)</strong><span><!-- --></span>';
    var myObj = $.cookie('PIRELLINURSESSION'+'_'+type);    
    var CompareSession = myObj.split("@");

    if(CompareSession[1].length==0) return 0;

    if(CompareSession[1]!=null) {
        var ar = CompareSession[1].split("|");
        if(ar.length==0) return 0;

        var quanti=0;
        for(i=0; i<ar.length; i++)
        {
            // DEBUG: alert('inside:' + ar[i]);
            if(ar[i].length>0 && ar[i]) quanti++;
        }
        return quanti;
    } else {
        return 0;
    }
}


/**
 * Inserisce un elemento nel carrello
 * indicato da type
 *
 * @param type
 * @param id_item
 */
function Nurun_addCompareItem(type, id_item)
{
    var myObj = $.cookie('PIRELLINURSESSION'+'_'+type);
    // DEBUG: alert(myObj);

    var CompareSession = myObj.split("@");
    if(CompareSession.length==0) return;

    var error = false;
    var ar = new Array();

    // --- Controllo che questo elemento non sia gia nel carrello
    if(CompareSession[1]!=null) {
        ar = CompareSession[1].split("|");
        for(i=0; i<=ar.length; i++)
        {
            var str = ar[i];
            // DEBUG: alert(str + '===' + id_item);
            if(str === id_item) {
                error = true;
            }
        }
    }

    // --- Prodotto gia  presente nel comparatore
    if(error) {
        alert(CompareLabels['exist']);
        return;
    }

    var max = Nurun_getCompareItems(type) + 1;
    if(max==5) {
        // --- shif array
        ar.shift();
    }

    // --- aggiungo elemento
    if(ar[0]=='' || ar[0]=='undefined') {ar[0]=id_item} else {
        ar.push(id_item);
    }

    var newSession = CompareSession[0]+'@'+ar.join('|');
    $.cookie('PIRELLINURSESSION'+'_'+type, newSession, {path: '/', expires: 30});


    // --- Redirect verso la pagina di compare
    if (document.location.href.indexOf('/pirellityre/') > 0)
    {
    	document.location.href = outComparePage[type];
    }
    else
    {
    	document.location.href = "../" + outComparePage[type];
    }
    	
}






function Nurun_testCookieValue()
{
    var myObj = $.cookie('PIRELLINURSESSION_CAR');
    alert(myObj);
}


function Nurun_removeCompareItem(type, id_item)
{
    var myObj = $.cookie('PIRELLINURSESSION'+'_'+type);
    // alert(myObj);

    var CompareSession = myObj.split("@");
    if(CompareSession.length==0) return;

    var outArray = new Array;
    var retArray = new Array;


    // --- Controllo che questo elemento non sia gia nel carrello
    if(CompareSession[1]!=null) {        
        var ar = CompareSession[1].split("|");

        // alert(ar.length);
        for(i=0; i<=ar.length; i++)
        {
            var str = ar[i];
            // DEBUG: alert(str + '===' + id_item);
            if(str != id_item && str!='' && str!='undefined') {

                // --- aggiungo elemento
                if(outArray[0]=='' || outArray[0]=='undefined') {outArray[0]=str} else {
                    outArray.push(str);
                }

            }

        }
    }

    // === Riverso tutti gli elementi BUONI di outArray su retArray
    for(aa=0; aa<outArray.length; aa++)
    {
        if(outArray[aa]!='' || outArray[aa]!=undefined || outArray[aa]!=null || typeof  outArray[aa]!=undefined)
        {
            if(outArray[aa]==undefined )continue;
            // DEBUG:  alert(aa + '-' + outArray[aa]);
            retArray.push(outArray[aa]);
        }
    }

    newElements = retArray.join('|');
    
    var newSession = CompareSession[0] + '@' + newElements;
    $.cookie('PIRELLINURSESSION'+'_'+type, newSession, {path: '/', expires: 30});

    // --- Redirect verso la pagina di compare
    document.location.href = outComparePage[type];
}


/**
 * Effettua le chiamate al server per il carrello "type"
 *
 * @param type
 */
function Nurun_callCompareContent(type,homeSiteLocale,homeStateLocale)
{
    var myObj = $.cookie('PIRELLINURSESSION'+'_'+type);
    if(myObj.match(/^"/)){
    	myObj=myObj.substring(1, myObj.length -1);
    }
    var CompareSession = myObj.split("@");

    if(CompareSession.length==0) return;

    var arSearch = new Array();

    // --- Controllo che questo elemento non sia gia nel carrello
    if(CompareSession[1]!=null) {
        var ar = CompareSession[1].split("|");

        for(i=0; i<ar.length; i++) {
            var str = ar[i];            
            if(str!='') {
                arSearch.push(str);
            }
        }

        // DEBUG: alert(arSearch.length);

        // === Inverto l'array
        arSearch.reverse();

        
        // === Effettuo le 4 chiamate al server
        for(i=0; i<4; i++) {

            // === Invio i dati al server
            DataSend = {
                'CompareType'   : type,
                'CompareItem'   : arSearch[i],
                'CompareSession' : myObj,
                'n_item'    : i+1
            }
           var url=serverCall[type]+'?homeSiteLocale='+homeSiteLocale+'&homeStateLocale='+homeStateLocale;
           // === Effettuo la chiamata al server
           $('#ItemCompare' + i).load(
        		    url,
                    DataSend
                );

        }   // for


    }
}



// --------------------------------------------------------
// === private Function
// --------------------------------------------------------

/**
 * Resituisce una stringa con caretteri random
 *
 * @private
 * @param int length
 * @param bool special      // return special chars
 */
function __randomChars(length, special) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  if(special == undefined){
      var special = false;
  }
  while(iteration < length){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    if(!special){
      if ((randomNumber >=33) && (randomNumber <=47)) {continue;}
      if ((randomNumber >=58) && (randomNumber <=64)) {continue;}
      if ((randomNumber >=91) && (randomNumber <=96)) {continue;}
      if ((randomNumber >=123) && (randomNumber <=126)) {continue;}
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  return password;
}


/**
 * Recupera i parametri provenienti dalla URL
 * passati come GET
 * gup = get URL Params
 *
 * @param String
 * @return String
 */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


function isValidType(strType)
{
    var valid = false;
    var arType = ['CAR', 'MOTORCYCLE', 'TRUCK', 'AGRO', 'MOTORSPORT'];
    for(i=0; i<arType.length; i++)
    {
        if(strType.toUpperCase() == arType[i]) valid=true;
    }
    return valid;
}


function isValidSubtype(strType, strSubtype)
{
    var valid = false;
    var strTypeField = strType.toUpperCase();
    if(!isValidType(strTypeField)) return false;

    // --- Definisco le combinazioni
    var arSubtype = new Array();
    arSubtype['CAR']        = new Array('CAR', 'SUV', 'VAN', 'MOTORSPORT');
    arSubtype['MOTORCYCLE'] = new Array('TRACK', 'ROAD', 'OFF-ROAD', 'SCOOTER', 'TUBES-MOUSSES');
    arSubtype['TRUCK']      = new Array('GOODS', 'PEOPLE');
    arSubtype['AGRO']       = new Array('', '', '', '');
    arSubtype['MOTORSPORT'] = new Array('', '', '', '');

    for(i=0; i<arSubtype[strTypeField].length; i++)
    {
        if(strSubtype.toUpperCase() == arSubtype[strTypeField][i]) valid = true;
    }
    return valid;
}

jQuery.extend({
    getValues: function(url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'html',
            async: false,
            success: function(data) {
                result = data;
            }
        });
        return result;
    }

});

//===  Funzione per formattare la data
function formatDate(dateToFormat)
{
	var m_names = new Array("Jan", "Feb", "Mar",
		"Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

	var d = new Date(dateToFormat);
	var curr_date = d.getDate();
	var curr_month = d.getMonth();
	var curr_year = d.getFullYear();
	var curr_hour = d.getHours();
	var curr_min = d.getMinutes();

	var res= (curr_year + " " + m_names[curr_month]	+ " " + curr_date);
	return res;
}

/**
 * Legge un feed RSS e lo disegna dentro un elenco puntato UL-LI
 *
 * @param path_to_feed      Persorso del feed RSS
 * @param max_feed          Numero di item che voglio rappresentare
 * @param destinationHTML   Nome (id) dell'elenco puntato su cui disegnare
 * 
 */
function read_RSS(path_to_feed, max_feed, destinationHTML)
{
    // === Per i dettagli vedi
    // === http://www.hovinne.com/blog/index.php/2007/07/15/132-jfeed-jquery-rss-atom-feed-parser-plugin

    jQuery.getFeed({
        url: path_to_feed,
        success: function(feed) {
            var html = '';

            for(var i = 0; i < feed.items.length && i < max_feed; i++) {

                var item = feed.items[i];

                html += '<li>'
                + '<p class="news-info">' + formatDate(item.updated) + '</p>'
                + '<p class="news-title"><a href="' + item.link + '" title="' + item.title + '">' + item.title + '</a></p>'
                + '<p class="news-details"><a href="' + item.link + '" title="Details">Details <strong>&gt;</strong></a></p>'
                + '</li>';

            }

            jQuery('#'+ destinationHTML).append(html);
        }
    })
}


