// ensure Google analytics get's the page count right even with Mobile Jquery
function update_ga_page_count(url) {
  try {
    if (!url) {
      if (location.hash){
        url = location.hash;
      } else {
        url = '/';
      }
    }
    _gaq.push( ['_trackPageview', url] );
  } 
  catch(error) 
  {
    // just to avoid the script blocking in case of error for now
    // later, we should add a log
  }
}


function attachMoreLink() {
   
    /* This will not work if there are sevel list views in the page */

    $('.more-link a').live('click', function(){

       $.mobile.pageLoading();
       var $more_link = $(this);
       var url = $more_link.attr('href');
       $.get(url, {}, function(data, textStatus, jqXHR){
          var $list = $more_link.parents('ul');
          $more_link.remove();
          $list.append(data);
          $list.listview('refresh');
          $.mobile.pageLoading(true);
          update_ga_page_count(url);
       })
       
       return false;

    })
}

/* Attache the event for when the page is loaded directly */
$(function(event){
    attachMoreLink();
    /* Attache the event for when the page is loaded by the jquery mobile ajax */
    $("div[data-role=page]").live('pagecreate', function(event){
        attachMoreLink();
    });

    // the search url is reformated to lool like a static page
    $('#header-search form').live('submit', function() {
      var url = $('#header-search form').attr('action');
      var searched_term = $(".ui-page-active #header-search #q").val();
      searched_term = searched_term.replace(/^\s+|\s+$/g,"");
      window.location.href = url + searched_term.replace(/\s+/g, '-');
      return false;
    });
})

$('[data-role=page]').live('pageshow', function (event, ui) {
  update_ga_page_count()



  /** Add search Terms to Redis **/
  if ( $('.ui-page-active .search-field').attr("value")) {

    if ( $('div.ui-page-active').find('h2').length != 0 ) {

        //add searched terms to Redis
        var $searched_terms = $('.ui-page-active .search-field').attr("value"); 
        $.get('/searched_terms/' + $searched_terms + '/increment/');

    }
  }

});










