urb = {};
urb.api = {};
urb.pager = {};
urb.login = {};
urb.reactions = {};
urb.search = {};
urb.newsletter = {};
isMagazine = false;
isVoxpop = false;

urb.pager.refreshCurrentList = function()
{
  $('#search_form').submit();
  return false;
};

urb.pager.setLevel = function(level)
{
	$('#search-level').val(level);
  $('#search-page').val(1);
  urb.pager.refreshCurrentList();
  return false;
	
};

urb.pager.setSort = function(sort)
{
  $('#search-sort').val(sort);
  $('#search-page').val(1);
  urb.pager.refreshCurrentList();
  return false;
}

urb.pager.setPagesize = function(pagesize)
{
  $('#search-pagesize').val(pagesize);
  $('#search-page').val(1);
  
  urb.pager.refreshCurrentList();
  return false;
}
urb.pager.setPage = function(page)
{
  $('#search-page').val(page);
  urb.pager.refreshCurrentList();
  return false;
};

urb.newsletter.validate = function()
{
  $('#nl-errors').html('');
  $('#nl-errors').hide();
    
  valid = true;
  if (!$('#nl-email').val().match(/^([^@]*)@([^\.]*)\.(.*)$/)) 
  {
     $('#nl-errors').append('<li>Courriel invalide</li>');
     valid = false;
  }
  
  if(valid)
  {
    var creds = new Object();
    creds['email'] = $('#nl-email').val();
    urb.api.register_newsletter(urb.newsletter.callback, creds);
  }
  else
    $('#nl-errors').fadeIn(500);
  
  return false;
}

urb.newsletter.callback = function(response)
{
  if(response.type == heap.SUCCESS)
  {
    $('#nl-errors').hide();
    $('#nl-errors').text( 'Vous êtes maintenant inscrit' );
    $('#nl-errors').fadeIn(500);
  }
  else
  {
    $('#nl-errors').hide();
    $('#nl-errors').text( response.msg );
    $('#nl-errors').fadeIn(500);
  };
}

urb.login.validate = function()
{
  $('#login-errors').html('');
  $('#login-errors').hide();
    
  valid = true;
  
  if(!$('#login-email').val() && !$('#login-password').val())
  {
    valid = false;
    $('#login-errors').append('<li class="ui-error">Veuillez remplir toutes les informations</li>');
  }
  
  else if (!$('#login-email').val().match(/^([^@]*)@([^\.]*)\.(.*)$/)) 
  {
     $('#login-errors').append('<li class="ui-error">Courriel invalide</li>');
     valid = false;
  }
  else if (!$('#login-password').val()) 
  {
    valid = false;
    $('#login-errors').append('<li class="ui-error">Mot de passe manquant</li>');
  }

  if(valid)
  {
    var creds = new Object();
    creds['email'] = $('#login-email').val();
    creds['password'] = $('#login-password').val();
    heap.api.users.login(urb.login.callback, creds);
  }
  else
    $('#login-errors').fadeIn(500);
  
  return false;
}

urb.login.callback = function(response)
{
  if(response.type == heap.SUCCESS)
  {
     document.location.href = document.location.href.replace(window.location.hash, ''); // '/';
  }
  else
  {
    $('#login-errors').hide();
    $('#login-errors').html( "<li class='ui-error'>"+response.msg+"</li>" );
    $('#login-errors').fadeIn(500);
  };
}

urb.api.register_newsletter = function(callback, params)
{
   jQuery.ajax({
        url: '/api/json/urbapi/register_newsletter',
        data: { parameters: JSON.stringify(params) },
        success: callback
   });
}

urb.reactions.parent = function(v)
{
  $('#reaction-parent').val(v);
}


urb.reactions.vote = function(atom_id, el, parent_id) {

  var params = new Object();

	params['atom_id'] = atom_id;
  params['type'] = 'vote';
  if (parent_id)
    params['parent_id'] = parent_id;
	


	heap.api.reactions.create( function(data){
    if (data._explicitType == "CentrifugeSuccess") 
    {
      votes = $(el).html();
      if ($('span', el)) {
        $('span', el).html();
      }
      var re = /\d+/g;
      votes = votes.match(re)[0];
      vote_update = "(" + (parseInt(votes) + 1) + ")";
      $(el).html(vote_update);
      if ( $('span', $('votecast_0')) ) {
        $('span', $('votecast_0')).html();
      }
      else {
        $(el).html(vote_update);
      }
      
      var msg = 'Ajout&eacute; aux favoris';
      if(data.data.parent_id){
            msg = 'Vote enregistr&eacute;';
      }
      
      $(el).attr('title', msg).tooltip({
        track: true,
        delay: 0,
        showURL: false,
        fade: 150
      });
      
    }
    else 
    {
      var msg = 'D&eacute;j&agrave ajout&eacute; aux favoris';
      
      if (data._explicitType == "CentrifugeError") 
      {
        if($(el).hasClass('votecast_0')) {
          msg = 'Vous avez d&eacute;j&agrave vot&eacute;';
                    
        } else {
          msg = 'D&eacute;j&agrave ajout&eacute; aux favoris';
        }
        $(el).attr('title', msg).tooltip({
          track: true,
          delay: 0,
          showURL: false,
          fade: 150
        });

      }
          $(el).attr('title',msg).tooltip({
              	track: true, 
                delay: 0,
              	showURL: false,
              	fade: 150
          });   
      

    } 
      $(el).trigger('mouseover');
      // $(el).attr('title',msg);
    }, params);
	return false;
};
    
urb.reactions.remove_vote = function(slug,caller) {
  heap.api.reactions.erase(urb.reactions.remove_voteCallback(caller),{slug:slug});   

  return false;
}


urb.reactions.remove_voteCallback = function(caller){ 
	$(caller).parents('li:first').remove(); // bye bye
}

urb.reactions.comment = function()
{
	var params = new Object();
	params['title'] = $('#reaction-title').val();
	params['body'] = $('#reaction-body').val();
	params['atom_id'] = $('#reaction-atom').val();
  params['_documents'] = $('#reaction-document').val(); 
  params['meta_name'] = $('#reaction-name').val();
  params['meta_email'] = $('#reaction-email').val();
	params['type'] = 'comment';

  var uid = $('#reaction-userid').val();

	if($('#reaction-parent').val())
		params['parent_id'] = $('#reaction-parent').val();


  if(!(uid > 0))
  {
	  if($('#reaction-name').val() == "")
    {
  		$('#errors').show().find('ul:first').html('<li class="ui-error">Veuillez entrer un nom pour commenter.</li>')
      return false;
    }

    var eml = $('#reaction-email').val();
    if(!((eml.indexOf(".") > 2) && (eml.indexOf("@") > 0)))
    {
  		$('#errors').show().find('ul:first').html('<li class="ui-error">Veuillez entrer un courriel valide.</li>');
      return false;
    }

  }

	if($('#reaction-body').val() == "") 
  {
		$('#errors').show().find('ul:first').html('<li class="ui-error">Veuillez entrer un commentaire.</li>')
    return false;
  }

    $('#errors').show().find('ul:first').html('<li class="ui-ok-progress">On envoie...</li>');
    $('#errors').show().find('ul:first').fadeIn(300);
  urb.api.comment( urb.reactions.commentCallback, params);

	return false;
}

urb.api.comment = function(callback, params)
{
   jQuery.ajax({
        url: '/api/json/urbapi/comment',
        data: { parameters: JSON.stringify(params) },
        success: callback
   });
}


urb.reactions.commentCallback = function(response)
{
  $('#reaction-errors').hide();
  
  if(response.type == heap.SUCCESS)
  {
    $('#errors').show().find('ul:first').html('<li class="ui-ok-progress">Commentaire envoyé! On recharge...</li>');
    $('#errors').show().find('ul:first').fadeIn(300);
    window.location.reload();
  }
  else
  {
    if(response.code == 'ERR_ALREADY_EXISTS')
    {
      $('#errors').show().find('ul:first').html("<li class='ui-error'>Un compte avec ce courriel existe déja! Veuillez vous authentifier.</li>");
      $('#errors').show().find('ul:first').fadeIn(300);
      $('#reaction-form').hide(300);
      $('#reaction-login').show(300);
    }
    else
    {
      $('#errors').show().find('ul:first').html("<li class='ui-error'>Une erreur est survenue. Essayez un peu plus tard.</li>");
      $('#errors').show().find('ul:first').fadeIn(300);
    }
  }
}

urb.reactions.voxpop = function()
{
  var params = new Object();
  params['title'] = $('#reaction-title').val();
  params['body'] = $('#reaction-body').val();
  params['atom_id'] = $('#reaction-atom').val(); 
  params['type'] = 'answer_text';
    
  heap.api.reactions.create( urb.reactions.voxpopCallback, params);   
  
  return false;
}

urb.reactions.voxpopCallback = function(response)
{
  $('#reaction-errors').hide();
  
  if(response.type == heap.SUCCESS) {
    window.location.reload();
  } else {
    $('#reaction-errors').text(response.msg);
    $('#reaction-errors').fadeIn(300);
  }
}


/*
  media reaction create
  Participation au concours 
*/
urb.reactions.video = function()
{
  var params = new Object();
  params['title'] = $('#reaction-title').val();
  params['body'] = $('#reaction-body').val();
  params['atom_id'] = $('#reaction-atom').val(); 
  params['type'] = 'answer_video';
  params['filename '] = $('#SWFUpload_0_2 .filename').text();
    
  heap.api.reactions.create( urb.reactions.videoCallBack, params);   
  
  return false;
}
urb.reactions.videoCallBack = function(response)
{
  $('#reaction-errors').hide();
  
  if(response.type == heap.SUCCESS) {
    window.location.reload();
    vox_pop.close();
  } else {
    $('#reaction-errors').text(response.msg);
    $('#reaction-errors').fadeIn(300);
  }
}

urb.search.setFilter = function(selector)
{
  $("#current_filter").val(selector.id.replace(/filter-/, ''));
  urb.search.newSubmit();
  
  return false;
}

urb.search.newSubmit = function()
{
  urb.pager.setPage(1);
  urb.search.submitForm();
}

urb.search.submitForm = function() {
	filter = $("#current_filter").val();
	if (!filter)
		filter = 'tous';
		
  if($("#sitesearch-value").hasClass('clean'))
	{
		if($("#sitesearch-value").val() == $("#sitesearch-value").attr('rel'))
		{
			$("#sitesearch-value").val('');
		}
	}
	value = URLEncode($("#sitesearch-value").val());
  
	$('#sitesearch').attr('action', '/recherche/' + filter + '/' + value);
	$('#sitesearch').submit();	
	return false;
}

urb.switchColor = function() {
	colorBg = null;
	
  if($('body').hasClass('light')){
    $('body').removeClass('light');
		$('.categories .thumbnail').css('opacity','0.8');
		
		outOpacity = 0.8;
		colorBg = 'dark'
		
		Cufon.replace('.magazines li');
		Cufon.replace('h2');
    Cufon.replace('.titleMag');
    //setCookie('__urb_bg_channel','dark');
		if(isMagazine){
			Cufon.set('color', '#DFE2DD').replace('span.titleMag');
			Cufon.set('color', '#FF0000').replace('span.color');
			Cufon.set('color', '#9A9A9A').replace('span.date');
		}else if(isVoxpop){
			Cufon.set('color', '#FFFFFF').replace('.vox-pop h2');
		}
  }else{
		
    $('body').addClass('light');
		$('.categories .thumbnail').css('opacity','1');
		
		outOpacity = 1;
		colorBg = 'light';
		
		Cufon.replace('.magazines li');
		Cufon.replace('h2');
    Cufon.replace('.titleMag');
		
		if(isMagazine){
			Cufon.set('color', '#282626').replace('span.titleMag');
			Cufon.set('color', '#FF0000').replace('span.color');
			Cufon.set('color', '#9A9A9A').replace('span.date');
		}else if(isVoxpop){
			Cufon.set('color', '#404040').replace('.vox-pop h2');
		}
  }
	
	//cookieFinal = checkCookie('__urb_bg_channel',channelName,colorBg);
	//setCookie('__urb_bg_channel',cookieFinal);
	
	if($('body').hasClass('light'))
		var iframe = '<iframe src="http://www.facebook.com/plugins/like.php?locale=fr_FR&app_id='+appId+'&amp;href='+currentUrl+'&amp;send=false&amp;layout=standard&amp;width=354&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=30" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:354px; height:30px;" allowTransparency="true"></iframe>';
	else
		var iframe = '<iframe src="http://www.facebook.com/plugins/like.php?locale=fr_FR&app_id='+appId+'&amp;href='+currentUrl+'&amp;send=false&amp;layout=standard&amp;width=354&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=30" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:354px; height:30px;" allowTransparency="true"></iframe>';
	
	$('span.iframe').html(iframe);
	
  return false;
};

var setCookie = function(cookieName,cookieValue){
	var date = new Date();
	date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
	$.cookie( cookieName, cookieValue, { path: '/', expires: date });
}


var checkCookie = function(COOKIE_NAME,channelName,colorBg){
	// get cookie
	var rep = '';
	rep = $.cookie(COOKIE_NAME);
	
	if(colorBg){
		newStr = '';
		found = false;
		
		if(rep != null){
			// split du cookie par la ',' pour les separer en channel
			arrRep = rep.split(',');
			//console.log('nb de channel dans la loop : '+arrRep.length)
			
			// parcourt du tableau des channels
			// veux trouver si le channel existe deja
			// si oui, remplacer sa valeur
			// si non, l'ajouter a la fin
			for(var i = 0; i < arrRep.length; i++){
				
				// separation du channel pour touver :
				// [0] => name [1] => color value 
				arrRepChannel = arrRep[i].split('|');
				//console.log('0 => '+arrRepChannel[0]+' || 1 =>'+arrRepChannel[1])
				if(arrRepChannel[0] == channelName){
					found = true;
					//console.log('found true');
					arrRepChannel[1] = colorBg;
				}
				newStr += arrRepChannel[0] + '|' + arrRepChannel[1];
				if(i!=arrRep.length-1){
					newStr += ',';
				}
			}
			if(found == false){
				//console.log('found false');
				newStr = rep + ',' + channelName + '|' + colorBg;
			}
			return newStr;
		}else{
			// si le cookie n'existe pas, creer la str avec les bonnes valeur
			newStr = channelName + '|' + colorBg;
			//console.log('cookie dont exist, must be : '+newStr);
			return newStr;
		}
		
	}
	
	if(rep != null){
		// split du cookie par la ',' pour les separer en channel
		arrRep = rep.split(',');
		
		// parcourt du tableau des channels
		for(var i = 0; i < arrRep.length; i++){
			// separation du channel pour touver :
			// [0] => name [1] => color value 
			arrRepChannel = arrRep[i].split('|');
			if(arrRepChannel[0] == channelName){
				found = true;
				return arrRepChannel[1];
			}
		}
	}else{
		rep = '';
	}
	return rep;
}


function URLDecode(encoded) {
  if (!encoded) return "";
  // Replace + with ' '
  // Replace %xx with equivalent character
  // Put [ERROR] in output if %xx is invalid.
  var HEXCHARS = "0123456789ABCDEFabcdef"; 
  var plaintext = "";
  var i = 0;
  while (i < encoded.length) {
    var ch = encoded.charAt(i);
    if (ch == "+") {
      plaintext += " ";
      i++;
    }
    else if (ch == "%") {
      if (i < (encoded.length-2) 
          && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
          && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
        plaintext += unescape( encoded.substr(i,3) );
        i += 3;
      }
      else {
        alert( 'Bad escape combination near ...' + encoded.substr(i) );
        plaintext += "%[ERROR]";
        i++;
      }
    }
    else {
      plaintext += ch;
      i++;
    }
  }; // while
  return stripslashes(plaintext);
};

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
      output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  };
  return output;
};

$.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function() {
	// Facebook connect
  $(".facebook-connect").live("click", function() {
    FB.login(function(response)
    {
      if (response.authResponse) // sdk 3.1
      {
        location.reload();
      }
    }, {scope:'email,user_photos'}); // sdk 3.1
    return false;
  });
	
	// Points System
	if ($.cookie("hide_points_popup") == null || $.cookie("hide_points_popup") == "false") {
    $("#points-overlay").show();
    $(".points-lightbox").show();
  }
  
  $(".points-lightbox a.points-close-icon").live("click", function() {
  	$("#points-overlay").hide();
    $(this).parents(".points-lightbox").hide();
    return false;
  });
  
  $("#points-learn-more").live("click", function() {
  	$("#points-explication").show();
		$("#points-explication").css("top", window.pageYOffset + 400);
	return false;
  });
  
  $("#points-explication a.points-close-icon").live("click", function() {
  	$("#points-explication").hide();
	return false;
  });
	
	$("#points-dont-show-cb").live("click", function() {
	  $.cookie("hide_points_popup", $(this).is(":checked"));
	});
});

Cufon.replace('.cufon');

