﻿/* Marionnaud */

var timeout    = 500,
    closetimer = 0,
    ddmenuitem = 0,
    ajaxXML = "",
    hasCalendar = "",
    eventsArray = [],                          // each position corresponds to a month and each position is filled with an array that has the events of each month
    availableXML = [],                        // has all the loaded xml list events. Each xml has a corresponding year.
    visualizedMonthOnDatepicker = new Date().getMonth(),
    ACTUAL_YEAR = new Date().getFullYear(),
    STREAM_XML_PAGE_ID = 220,
    ajaxCallEnded = true,                      // controls the ajax calls process
    from = to = more = "";                    // from: saves the start event day text
                                              // to: saves the end event day text
                                              // more: saves the more info event text
 
 
 
$(function() {
  correctMenus("#mainmenu");
  
  // calendar
  $(".calendardate a").each(function(i) {
    $(this).click(function() {
      $(".event").slideUp();
      $(".event:eq(" + i + ")").slideDown();
    });
  });
  $(".calendardate a:first").trigger("click");

  // Open/close links
  $("table.openCloseBar").parents("div.Paragraph").find("div.ParagraphModule").hide();
  $("table.openCloseBar a").click(function() {
    $(this).parent().find("a").toggle();
    $(this).parents("div.Paragraph").find("div.ParagraphModule").slideToggle();
  });

  //Homepage Product Scroll
  $("#scroller").scrollable({circular: true, speed: 650}).autoscroll({ autoplay: true, interval:3500 });

  // correct news paging
  $(".destaquepages a b, .pages a b").parent().css({"padding-left": "0", "padding-right": "0"});

  if( $('button[rel]').length )
    $('button[rel]').overlay({mask: '#621a4a'});
  
  /* correctionStart - sergio.f - 30-05-2011 (implement the authentication)  */
    if( $( 'form[name=ExtUserForm]' ) )
      showHideAuthenticationForm();
  /* correctionEnd */

  /* correctionStart - sergio.f - 02-06-2011 (implement the events)  */
    if( $( 'div#datepicker' ).length > 0 )
      setupDatepicker();
    
    if( $( 'table#scheduledEvents' ).length > 0 ) {
      getAllEvents( STREAM_XML_PAGE_ID, ACTUAL_YEAR );
      correctEventDescription();
    }
  /* correctionEnd */
  
  // check if the user is watching the an event details. If so, move the poster link under the image
  var eventPoster = $( '#scheduledEvent .eventPoster' );
  
  if( eventPoster.length > 0 && $( '#scheduledEvent .calendar_Image' ).length > 0 ) {
    $( '#scheduledEvent .calendar_Image' ).after( $( eventPoster ) );
    $( eventPoster ).show();
  }
});

$(window).ready(function () {
  if ($.browser.msie)
    window.setInterval($("div.clear").attr("class","clear"), 1000);
  if (typeof(hasCalendar) !== 'undefined') {
    $('#sitemap > li').each(function() {
      $(this).children('a').attr('href', 'javascript:void(0);');
    });
  }
});

/* enables the actions on the menu */
function activateActionsOnMenu() {
  $('#mainmenu ul:first > li:not( .inpath )').bind('mouseover', jsddm_open);
  $('#mainmenu ul:first > li:not( .inpath )').bind('mouseout',  jsddm_timer);
  
  // Slides up/down menu when the user clickes the arrow
  $( '#mainmenu ul.pageLevel1 > li.inpath div' ).click( function() {
    var clickedDiv = $( this );
    
    if( $( clickedDiv ).hasClass( 'closeMenu' ) ) {
      $( clickedDiv ).parent().find( 'ul' ).slideUp( 'slow', function() {
        $( clickedDiv ).removeClass( 'closeMenu' );
        $( clickedDiv ).addClass( 'openMenu' );
      });
    }
    else {
      if( $( clickedDiv ).hasClass( 'openMenu' ) ) {
        $( clickedDiv ).parent().find( 'ul' ).slideDown( 'slow', function() {
          $( clickedDiv ).removeClass( 'openMenu' );
          $( clickedDiv ).addClass( 'closeMenu' );
        });
      }
    }
  });
}

function addXFBML() {
  $("div.verprodutosrecomendar").append('<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="" send="true" width="450" show_faces="true" font=""></fb:like>');
}

/* resets the general search box text to its default value */
function checkIfEmpty( input, defaultValue ) {
  if( ( $( '#' + input ).val() == "" ) || $( '#' + input ).val().toLowerCase() == defaultValue.toLowerCase() )
      $( '#' + input ).val( defaultValue );
}

/* clears the general search box text */
function clearField( input, defaultValue ) {
  if( $('#'+input).val().toLowerCase() == defaultValue.toLowerCase() )
      $('#'+input).val("");
}

/* shows only the first three lines of the event description and includes the "read more" link */
function correctEventDescription() {
  $( 'table#scheduledEvents .calendar_Text' ).each( function() {
  
    // check if the description takes more than three lines
    if( $( this ).height() > 42 ) {
      var eventLink = $( this ).find( 'a.morenews' );
      
      // show only the first 140 characters
      $( this ).text( $( this ).text().substr( 0, 140 ) + "... " ).append( eventLink );
    }
    
    // the description was hidden by default so that the user doesn't see the all description than the smaller introduction
    $( this ).show();
  });
}

//Pagging_function
function createPages(pageId, numPages, currentPage, pageLimit, prevPageHref, nextPageHref, groupId) {
  var pagingUl = '<ul class="PagingList">',
      pageBegin,
      pageEnd;
    
  if (groupId != '') groupId = "&GroupId=" + groupId;
  if (numPages > 1) {
    if (prevPageHref.search("none") == -1) pagingUl += '<li><a href="' + prevPageHref + '">Anterior<\/a><\/li>';
    
    if(numPages > pageLimit) {
      if ((pageLimit%2) == 0) pageLimit++;
      
      pageBegin = currentPage - (pageLimit - 1)/2;
      if(pageBegin <= 0) pageBegin = 1;
      
      if(pageBegin >= (numPages - (pageLimit - 1)/2)) pageBegin = numPages - pageLimit +1;
        
      pageEnd = pageBegin + pageLimit - 1;
        
      if (pageEnd >= numPages) {
        pageEnd = numPages;
        pageBegin = numPages - pageLimit + 1;
      }
    }
    else {
      pageBegin = 1;
      pageEnd = numPages;
    }
    
    for (i = pageBegin; i <= pageEnd; i++) {
      i = ( i < 10 ) ? "0" + i.toString() : i;
      if(i != currentPage) {
       pagingUl += '<li><a href="/Default.aspx?ID=' + pageId + groupId + '&PageNum=' + i + '">' + i + '<\/a><\/li>';
      }
      else {
        pagingUl += '<li class="active"><a href="/Default.aspx?ID=' + pageId + groupId + '&PageNum=' + i + '">' + i + '<\/a><\/li>';
      }
    }
    
    if (nextPageHref.search("visible") == -1) pagingUl += '<li id="proximo"><a href="' + nextPageHref + '">Próximo<\/a><\/li>';
    
    pagingUl += '</ul>';
    $("div.PagingHolder").html(pagingUl);
  }
}

//CorrectMenus

function correctMenus(selector) {

  var menuWidth = $(selector).width(),
      totalLiWidth = 0,
      $li = $(selector + " > ul > li");

  $li.each(function() {
    totalLiWidth += $(this).outerWidth(true);
  });

  // Work out how much padding we need and account for rounding errors, the error is going to be forced into the first tab.
  var requiredPadding = Math.floor(((menuWidth-totalLiWidth)/$li.length)/2),
      leftRoundingErrorFix = Math.round((menuWidth-((requiredPadding*$li.length*2)+totalLiWidth))/2),
      rightRoundingErrorFix = Math.floor((menuWidth-((requiredPadding*$li.length*2)+totalLiWidth))/2);
  
  // Apply padding to list items
  $li.each(function(i) {
    if(i == 1)
      $(this).find("a").css('padding-left',requiredPadding+leftRoundingErrorFix+'px').css('padding-right',requiredPadding+rightRoundingErrorFix+'px');
    else
      $(this).find("a").css('padding-left',requiredPadding+'px').css('padding-right',requiredPadding+'px');
  });
  
  activateActionsOnMenu();
}

/* makes an Ajax call to a specific page specified by the pageID argument.
   The "pageSlide" argument refers to, for example:
   -1: previous event/day/month/year
    0: current event/day/month/year
    1: next event/day/month/year
 */
function getAllEvents( pageID, xmlYear ) {
  var pageSlide = xmlYear - ACTUAL_YEAR;

  ajaxCallEnded = false;
  
  $.ajax({
    type: 'GET',
    url: location.protocol + "//" + location.hostname + "/Default.aspx?ID=" + pageID + "&Page=" + pageSlide,
    error: function( xhr, status, errorThrown ) {
      alert( errorThrown + '\n' + status + '\n' + xhr.statusText );
    },
    success: function( data ) {
      ajaxCallEnded = true;
      
      if( $.browser.msie && typeof data == "string" ) {
        ajaxXML = new ActiveXObject( "Microsoft.XMLDOM" );
        ajaxXML.async = false;
        ajaxXML.loadXML( data );
      }
      else
        ajaxXML = data;

      // object that has the year and the corresponding received xml
      var receivedXML = {
        year: xmlYear,
        xml: ajaxXML
      };

      // add the xml to the available xml array
      availableXML.push( receivedXML );

      readXML( ajaxXML, xmlYear );
    }
  });
}

function jsddm_canceltimer() {
  if(closetimer) {
    window.clearTimeout(closetimer);
    closetimer = null;
  }
}

function jsddm_close() {
  if(ddmenuitem) ddmenuitem.hide();
}
 
function jsddm_open() {
  jsddm_canceltimer();
  jsddm_close();
  ddmenuitem = $(this).find('ul:first').show();
}
 
function jsddm_timer() {
  closetimer = window.setTimeout(jsddm_close, timeout);
}

/* displays an alert informing that there was a loggin error and sets the submited username value to the login form */
function loginFailed( submittedUsername, errorMessage ) {
  $( '#footermenu form #username' ).val( submittedUsername );
  alert( errorMessage );
}

/* reads the received xml and creates an object for each event and saves in an array */
function readXML( xml, xmlYear ) {
  var actualMonth = month = -1,    // actualMonth: has the month of the previous event
                                  // month: has the month of the actual event
      events = [];                // array with the events that occur on the same day
  
  // go through each event on the xml and save the data from each one
  $( xml ).find( 'event' ).each( function( i ) {
    var startDate = $( this ).find( 'startDate' ),
        endDate = $( this ).find( 'endDate' ),
        event = {
          eventStartDay: $( startDate ).attr( 'day' ),
          eventStartMonth: $( startDate ).attr( 'month' ),
          eventStartYear: $( startDate ).attr( 'year' ),
          eventEndDay: $( endDate ).attr( 'day' ),
          eventEndShortMonth: $( endDate ).attr( 'shortMonthName' ),
          eventEndYear: $( endDate ).attr( 'year' )
        };
      
      month = parseInt( $( startDate ).attr( 'month' ) );
      
      // first event
      if( month != actualMonth && i == 0 ) {
        actualMonth = month;
        events.push( event );
      }
      else {
        // check if the current event occurs on other month than the previsouly checked
        if( month != actualMonth ) {
          /* insert the events array to the correct position
             ex: eventsArray[0] to eventsArray[11] - current year
                 eventsArray[12] to eventsArray[23] - next year
                 etc...
          */
          eventsArray[( actualMonth - 1 ) + ( 12 * ( xmlYear - ACTUAL_YEAR ) )] = events;
          
          // clear the array
          events = [];
          
          events.push( event );
          actualMonth = month;
        }
        else
          events.push( event );
      }
  });
  
  /* save the last events
     ex: eventsArray[0] to eventsArray[11] - current year
         eventsArray[12] to eventsArray[23] - next year
         etc...
  */
  if( $( events ).length > 0 )
    eventsArray[( actualMonth - 1 ) + ( 12 * ( xmlYear - ACTUAL_YEAR ) )] = events;
    
  showDaysEventsOnDatepicker( visualizedMonthOnDatepicker, xmlYear );  
}

function searchReposition() {
  $("#searchproduct").appendTo("#header");
  if ($("#headersubmenu").length) {
    $("#searchproduct").css("top", "145px");
  }
}

/* initializes the jQuery datepicker */
function setupDatepicker() {
  $( '#datepicker' ).datepicker({
    minDate: 0,
    onChangeMonthYear: function( year, month, inst ) {
      var xmlIsAvailable = false;
      
      $( '#datepickerHolder table.ui-datepicker-calendar th:first' ).css( 'border-left', 'none' );
      
      // update datepicker visualized month variable
      visualizedMonthOnDatepicker = month - 1;

      // check if the xml related to the year the user wants to see has already been loaded
      for( var i = 0; i < availableXML.length; i++ ) {        
        if( availableXML[i].year == year ) {
          xmlIsAvailable = true;
          break;
        }
      }
      
      // if the xml has been loaded
      if( xmlIsAvailable ) {
        // let the datepicker reload (wait 1 milisecond) and indicate the days that have events
        setTimeout( function() {
          showDaysEventsOnDatepicker( visualizedMonthOnDatepicker, year );
        }, 1 );
      }
      else {
        // load the new xml only if the previously ajax call has ended.
        if( ajaxCallEnded )
          getAllEvents( STREAM_XML_PAGE_ID, year );
      }
    },
    // activate the click event on a day so that the user can see the events that happen on that day
    onSelect: function( dateText, inst ) {
      $( '#datepickerHolder table.ui-datepicker-calendar th:first' ).css( 'border-left', 'none' );
      
      showEventsOnThisDay( dateText );

      // let the datepicker reload (wait 1 milisecond) and indicate the days that have events
      setTimeout( function() {
        var dateArray = dateText.toString().split( '/' );
        showDaysEventsOnDatepicker( dateArray[1] - 1, dateArray[2] );
      }, 1 );
    }
  });
  
  // set the default datepicker language to Portuguese
  $.datepicker.regional[ 'pt-BR' ];
  
  // save global info
  from = $( 'table#scheduledEvents .calendar_Date .from:first' ).text(),
  to = $( 'table#scheduledEvents .calendar_Date .to:first' ).text(),
  more = $( 'table#scheduledEvents .calendar_Text .morenews:first' ).text(),
  
  // correct the datepicker holder div height
  $( '#datepickerHolder' ).css( 'height', ( $( '#maincontainer' ).height() - 33 ) + 'px' );
  
  $( '#datepickerHolder table.ui-datepicker-calendar th:first' ).css( 'border-left', 'none' );
}

function setupRegistration( name, email ) {
  $( '#newslettersubscribe input[name=AccessUserName]' ).val( name ).attr( {'onfocus': 'clearField(this.id, "' + name + '")', 'onblur': 'checkIfEmpty(this.id, "' + name + '")'} );
  $( '#newslettersubscribe input[name=AccessUserEmail]' ).val( email ).attr( {'onfocus': 'clearField(this.id, "' + email + '")', 'onblur': 'checkIfEmpty(this.id, "' + email + '")'} );
}

/* indicates on the datepicker (by adding the classes "ui-state-active" and"hasEvent") the days that have events */
function showDaysEventsOnDatepicker( monthToShow, xmlYear ) {
  var event,
      eventDay = eventMonth = eventYear = -1,
      arrayPosition = monthToShow + ( 12 * ( xmlYear - ACTUAL_YEAR ) );

  // check if there are events on this month
  if( eventsArray[arrayPosition] && eventsArray[arrayPosition].length ) {

    // iterate every event
    for( var i = 0; i < eventsArray[arrayPosition].length; i++ ) {
      eventDay = eventsArray[arrayPosition][i].eventStartDay;
      eventMonth = eventsArray[arrayPosition][i].eventStartMonth - 1;
      eventYear = eventsArray[arrayPosition][i].eventStartYear;
      
      // search the corresponding selectable date on the datepicker and indicate the event
      $( 'table.ui-datepicker-calendar td' ).each( function() {
        if( $( this ).attr( 'onclick' ) ) {
          var anchorDay = $( this ).find( 'a' );
          
          if( $( this ).attr( 'onclick' ).toString().indexOf( "," + eventMonth + "," + eventYear + "," ) != -1 && $( anchorDay ).text() == eventDay.toString() ) {
            $( anchorDay ).addClass( 'hasEvent' );
            return;
          }
        }
      });
    }
  }
}
  
// shows the events that happen on the selected day
function showEventsOnThisDay( date ) {
  var eventsTable = "<table id='scheduledEvents' cellspacing='0' cellpadding='0' border='0' width='100%'>",
      event = "",
      calendarImage = "",
      calendarTitle = "",
      calendarInfo = "",
      startDate = "",
      endDate = "",
      imagePath = "",
      description = "",
      selectedDay = "",
      selectedMonth = "",
      selectedYear = "",
      eventDay = "",
      eventMonth = "",
      eventYear = "",
      dateArray = [],
      selectedDate, eventDate;
  
  dateArray = date.toString().split( '/' );
  selectedDay =  dateArray[0];
  selectedMonth = dateArray[1];
  selectedYear = dateArray[2];
  selectedDate = new Date( selectedYear, selectedMonth - 1, selectedDay );
  
  // show the selected date
  $( '#contents .ParagraphText h1.h1' ).text( selectedDay + " " + $( '.ui-datepicker-title span.ui-datepicker-month' ).text() + " " + $( '.ui-datepicker-title span.ui-datepicker-year' ).text() );

  // get the correct xml depending on the year that the user is seeing
  ajaxXML = availableXML[selectedYear - ACTUAL_YEAR].xml;
  
  $( ajaxXML ).find( 'event' ).each( function() {
    
    eventDay = $( this ).find( 'startDate' ).attr( 'day' );
    eventMonth = $( this ).find( 'startDate' ).attr( 'month' );
    eventYear = $( this ).find( 'startDate' ).attr( 'year' );
    eventDate = new Date( eventYear, eventMonth - 1, eventDay );
    
    // show only the events that happen on the day that the user selected
    if( eventDate.getTime() == selectedDate.getTime() ) {
    
      // get CDATA value from event's description
      if( !$.browser.msie ) {
        description = $( this ).find( 'description' ).html();
        
        // clean the text: removes <![CDATA[ from the beginning and removes ]]> from the end
        description = description.substr( description.indexOf( "<!--[CDATA[" ) + 11, description.indexOf( "]]" ) - 11 );
      }
      else
        description = $( this ).find( 'description' ).text();

      /* build the event html */
      imagePath = ( $( this ).attr( 'image' ) == "" ) ? $( this ).attr( 'defaultImage' ) : $( this ).attr( 'image' );
      calendarImage = "<div class='calendar_Image'><a href='" + $( this ).find( 'eventLink' ).text() + "'><img src='/admin/public/getimage.aspx?Image=" + imagePath + "&amp;Width=180&Compression=80&amp;Format=jpg&amp;ColorSpace=RGB' alt='" + $( this ).attr( 'title' ) + "' /></a></div>";
      calendarTitle = "<div class='calendar_Title'>" + $( this ).attr( 'title' ) + "</div>";
      startDate = $( this ).find( 'startDate' );
      endDate = $( this ).find( 'endDate' );
      calendarInfo = "<div class='calendar_Info'><div class='calendar_Date'><span class='from'>" + from + "</span> " + $( startDate ).attr( 'day' ) + " " + $( startDate ).attr( 'shortMonthName' ) + " " + $( startDate ).attr( 'year' ) + " <span class='to'>" + to + "</span> " + $( endDate ).attr( 'day' ) + " " + $( endDate ).attr( 'shortMonthName' ) + " " + $( endDate ).attr( 'year' ) + "</div><div class='calendar_Hour'>" + $( startDate ).attr( 'hour' ) + "h" + $( startDate ).attr( 'minute' ) + "<span class='calendar_Identity'>" + $( this ).attr( 'title' ) + "</span></div><div class='calendar_Text' style='display: block;'>" + description + " <a class='morenews' href='" + $( this ).find( 'eventLink' ).text() + "'>" + more + "</a></div></div>";
      event = "<tr><td>" + calendarImage + "</td><td>" + calendarTitle + calendarInfo + "</td></tr>"
      /* end of the event html */
      
      eventsTable += event;
    }
  });
  
  // check if the selected day has events. If not, show the no events message
  eventsTable += ( $( eventsTable ).find( '.calendar_Image' ).length > 0 ) ? '</table>' : '<tr><td>' + $( ajaxXML ).find( 'NoEvents' ).text() + "</td></tr></table>" ;
  
  // insert the new events table after the next four events table
  $( 'table#scheduledEvents' ).after( eventsTable );
  
  // remove the next four events table so that only the events that occur on the current day show up
  $( 'table#scheduledEvents' ).first().remove();
  
  correctEventDescription();
}
  
/* correctionStar - sergio.f 25-05-2011 - fix footer menu */
/* shows and hides the authentication form that's on the footer */
function showHideAuthenticationForm() {
  $( '.footermenu li a.firstitem' ).click( function( event ) {
    var authenticationFormHolder = $( this ).next();

    // check if the form exists and is visible
    if( $( authenticationFormHolder ) && $( authenticationFormHolder ).hasClass( 'bottomfooter_bg' ) && !$( authenticationFormHolder ).is( ':visible' ) ) {
      $( this ).addClass( 'authenticationFormVisible' );
      $( authenticationFormHolder ).show();

      // add the event listener to hide the form
      $( 'html' ).click( function( event ) {
        var target = event.target;
        
        // check if the user clicked anywhere except the authentication option
        if( $( target ).parents( '.footermenu' ).length == 0 || ( $( target ).parents( '.footermenu' ).length == 1 && $( target ).parents( 'li' ).children().length <= 1 ) ) {
          $( '.footermenu li .bottomfooter_bg' ).hide();
          $( '.footermenu li a.firstitem' ).removeClass( 'authenticationFormVisible' );
        }
      });
    }
  });
}
/* correctionEnd */

function submitFilter(param) {
  var genderSelected = $("#productTypeGender option:selected").val(),
      searchQuery = '';
 
  if (param == 'desc') {
    $('input[name=SortOrder]').val(param);
  }
  $("#FieldName").attr("name", genderSelected);
  $("#FieldType").attr("name", genderSelected + "_Type");
  $("form[name=eComSearchForm]").submit();
}

function updateGroupLinks(groupName) {
  //$("#submenu li a").removeAttr("onclick");
/*  $("#submenu li").each(function(i) {
    if($(this).find("a").text() == groupName) {
      $("div.produtosimage:eq(" + i + " a").removeAttr("onclick");
      $("div.produtosimage:eq(" + i + " a").click(function(e) {
        alert(i);
e.preventDefault();
      });
      return false;
    }
  });*/
}
  
function updatePath(item) {
  $("#path ul li:last").append('<ul><li class="lastitem"><a href="javascript:void(0)">' + item + '</a></li></ul>');
}

function validateNewsletter(parId, name, email) {
  var submitForm = true,
      dwValidateFuntion = "ValidateForm_" + parId,
      input = $("#AccessUserEmail_" + parId).val(),
      input2 = $("#AccessUserName_" + parId).val(),
      messageRequiredMail = $(".validator_requiredAccessUserEmail_" + parId).text(),
      messageAcessMail = $(".validator_correctAccessUserEmail_" + parId).text();
  
  if (input2 == '' || input2 == name) {
    alert("O nome é obrigatório");
    submitForm = false;
  }
  if (input == '' || input == email) {
    alert("O e-mail é obrigatório");
    submitForm = false;
  }
  else if (!validateEmail(input)) {
    alert("O e-mail introduzido é inválido");
    submitForm = false;
  }
  if (submitForm) {
    submitForm = eval(dwValidateFuntion + '()');
  }
  
  return submitForm;
}

function ValidateEcomSearch(errorMessage, defaultBrandValue, defaultKeywordValue) {
  var submitForm = true,
      brandValue = $("#searchBrand").val(),
      keywordValue = $("#searchText").val();
  
  if ((brandValue == '' || brandValue == defaultBrandValue) && (keywordValue == '' || keywordValue == defaultKeywordValue)) {
    alert(errorMessage);
    submitForm = false;
  }
  else {
    if (brandValue == '' || brandValue == defaultBrandValue) $("#searchBrand").val('');
    if (keywordValue == '' || keywordValue == defaultKeywordValue) $("#searchText").val('');
  }
  
  return submitForm;
}

function validadeLogIn( defaultUsernameValue, defaultPasswordValue, errorMessage ) {
  if( $( '#username' ).val().replace(/^\s*|\s*$/g,'') == "" || $( '#password' ).val().replace(/^\s*|\s*$/g,'') == "" || ( $( '#username' ).val().toLowerCase() == defaultUsernameValue.toLowerCase() && $( '#password' ).val().toLowerCase() == defaultPasswordValue.toLowerCase() ) ) {
    alert( errorMessage );
    return false;
  }
  else
    return true;
}
  
function validateMarionnaudCard(errorMessage, defaultInput1Value, defaultInput2Value) {
  var submitForm = true,
      cardNumberValue = $("input[name=codeclient]").val(),
      zipCodeValue = $("input[name=codepostal]").val();
  
  if (cardNumberValue == '' || cardNumberValue == defaultInput1Value || zipCodeValue == '' || zipCodeValue == defaultInput2Value) {
    alert(errorMessage);
    submitForm = false;
  }
  
  return submitForm;
}

/* checks if the general search box value isn't empty or if its not equal to the default value */
function ValidateSearch( input, errorMessage, defaultValue ) {
  if( ( $( '#' + input ).val() == "" ) || ( $( '#' + input ).val().toLowerCase() == defaultValue.toLowerCase() ) ) {
    alert( errorMessage );
    return false;
  }
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}

