/*
JQuery para tratar setar cookie de afiliados ou desconto.
*/

$(document).ready(checkUrl);


function checkUrl() {
   checkSource();
   checkReferral();
   checkDesconto();
}

var href = window.location.href;

function gup(key, prefix){
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = prefix + key + "=([^?&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( href );
  if( results == null )
    return "";
  else
    return results[1];
}

function getQueryParam(key){
   return gup(key,'[?&]');
}

function getHashParam(key){
   return gup(key,'[#&]');
}

function checkSource() {
   var gclid = getQueryParam('gclid');
   if (gclid) callHandler('source', gclid);
}

function checkReferral() {
   var afiliado = getHashParam('a');
   if (afiliado) callHandler('afiliado', afiliado);
}

function checkDesconto() {
   var desconto = getHashParam('d');
   if (desconto) callHandler('desconto', desconto);
}

var url_prefix = 'http://' + window.location.host
             + window.location.pathname + 'pedido/async/';

function callHandler(type, value) {
   var data = {
      value: encodeURIComponent(unescape(value))
   };
   data[type] = 1;
   var url = url_prefix + type;
   $.post(url, data, function(){
      window.location.hash = '';
   });
}


