// Prepare

jQuery(document).ready(function(){
	

	
jQuery("a").live("click",function(event){
    
    var section = "";
    if(this.href.indexOf("?")>0)
          section = this.href.split('?')[1].split('=')[0];
    
    if(this.href.indexOf(window.homeURL)>=0 && 
	     this.href.indexOf('/wp-')<0 &&
	     !jQuery(this).hasClass("comment-reply-link") && 
       !jQuery(this).hasClass("gocheckout") &&
       !jQuery(this).hasClass("go_to_checkout") &&
       !jQuery(this).hasClass("thickbox") &&
       !jQuery(this).hasClass("jaw_years") &&
       !jQuery(this).hasClass("nyroModalClose") &&
       !jQuery(this).hasClass("download-link") &&
       this.href.indexOf("ajax")<0 && 
       (this.href.indexOf("#")<0 || this.href.indexOf("#comment-")>=0)
       
        /*&&
       (section =='m'||
           section =='p'||
           section =='cat'||
           section =='tag'||
           section.indexOf('wpsc')>=0 ||
           section =='page_id' ||
           this.href == (window.homeURL+"/") || 
           this.href == window.homeURL)*/
           
            ){ 
	                if(event.which){
                     if(event.which!=1) return; 
                  } else if(button!=1){
                    return;
                  }
	                  event.preventDefault();
	                  this.blur();
	                  var url = this.href;
	                  url = decodeURI(url); 
	                  
	                  var urlAux = url;
	                  var u2 = "";
	                  if(url.indexOf("#")>=0){
	                  	urlAux = url.split("#")[0];
	                  	u2 = url.split("#")[1];
	                  	if(u2.indexOf("?")>=0){
	                  		u2 = "#" + u2.split("?")[0];	
	                  	}
	                  }
								    
								    var stateObj = { ajax: "ajax", url: urlAux, target: "#"+u2 };
													                  
													               
										window.History.pushState(stateObj, "",urlAux);
		
	                  loadPage(urlAux);
		}

});
    
    if(jQuery("#searchform").length>0)
   	 jQuery("#searchform")[0].action = "javascript:submitSearch('?s='+document.getElementById('s').value)";
    
    jQuery("form.remove_item_form input.remove_button").live("click",function(){
					parent_form = jQuery(this).parent("form.remove_item_form");
					form_values = "ajax=true&";
					form_values += jQuery(parent_form).serialize();
					jQuery.post( 'index.php', form_values, function(returned_data) {
							eval(returned_data);
					});
				return false;
			});
			
	jQuery("#current_country").attr("onchange","");		
		
	// Submit the product form using AJAX
	jQuery("tr.wpsc_change_country td form").live('submit', function(e) {
		e.preventDefault();
		var actionUrl = this.action;
		var viewArr = jQuery(this).serializeArray()
    var view = {},viewAjax={};
	
	  for (var i in viewArr) {
	    view[viewArr[i].name] = viewArr[i].value;
	    viewAjax[viewArr[i].name] = viewArr[i].value;
	  }
	  jQuery('div.entry-content').fadeOut(300,function(){
			jQuery('div.entry-content').load(actionUrl+" div.entry-content > *",view,function(responseText, textStatus, xhr){
			jQuery("#current_country").attr("onchange","");	
		
		     	jQuery('div.entry-content').fadeIn(300);
		   });
		});
		
	
	});
	
	
	// Submit the product form using AJAX
	jQuery("form.adjustform.qty").live('submit', function(e) {
		e.preventDefault();
		var actionUrl = this.action;
		var viewArr = jQuery(this).serializeArray()
    var view = {},viewAjax={};
	
	  for (var i in viewArr) {
	    view[viewArr[i].name] = viewArr[i].value;
	    viewAjax[viewArr[i].name] = viewArr[i].value;
	  }
	  
	  viewAjax.ajax = true;
	
		
		jQuery.post(actionUrl,viewAjax,function(responseText, textStatus, xhr){
	     	eval(responseText);
	   });
	
	
		jQuery('div.entry-content').fadeOut(300,function(){
			jQuery('div.entry-content').load(actionUrl+" div.entry-content > *",view,function(responseText, textStatus, xhr){
				jQuery("#current_country").attr("onchange","");	
		     	jQuery('div.entry-content').fadeIn(300);
		   });
		});
		
		
		return false;
		
	});
	
	// Submit the product form using AJAX
	jQuery("form.adjustform.remove").live('submit', function(e) {
		e.preventDefault();
		var actionUrl = this.action;
		var viewArr = jQuery(this).serializeArray()
    var view = {},viewAjax={};
	
	  for (var i in viewArr) {
	    view[viewArr[i].name] = viewArr[i].value;
	     viewAjax[viewArr[i].name] = viewArr[i].value;
	  }
	  
	  
		
		 //Una llamada para actualizar el widget
		viewAjax.ajax = true;
		
		jQuery.post(actionUrl,viewAjax,function(responseText, textStatus, xhr){
	     	eval(responseText);
	   });
	   
	   
	   //Una llamada para actualizar el carrito
		jQuery('div.entry-content').fadeOut(300,function(){
			jQuery('div.entry-content').load(actionUrl+" div.entry-content > *",function(responseText, textStatus, xhr){
				jQuery("#current_country").attr("onchange","");	
		
			   	jQuery('div.entry-content').fadeIn(300);
		   });
		});
		
		return false;
		
	});
	
			

});
// Bind to StateChange Event

window.History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
    var State = window.History.getState(); // Note: We are using History.getState() instead of event.state
    //window.History.log(State.data, State.title, State.url);
    
    loadPage(State.url);
});

function getHTTPObject() {
  var xmlhttp;
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var isWorking = false;
var http = getHTTPObject();

function updateMenu(url){

  jQuery(".menu-item").removeClass("current_page_item current-menu-item current-menu-parent current-menu-ancestor current_page_parent current_page_ancestor");

  jQuery(".menu-item").each(function(e){
      
    var address = jQuery(this).find("a:first");
    if(address){
      var itemurl = address.prop("href");
      if(url == itemurl){
        jQuery(this).addClass("current_page_item current-menu-item");
        jQuery(this).parents(".menu-item").each(function(p){
          jQuery(this).addClass("current-menu-parent current-menu-ancestor current_page_parent current_page_ancestor");
        });
        return false;
      }  
    }
    
  });
}



function loadPage(url){
  if(!isWorking){
    
   
  	hideMenu();
		
   
					                  	
    http.open('GET',url,true);
    isWorking=true;
   
    http.onreadystatechange=showPage;
    		

		jQuery("#fancy_notification").remove(); 		 						  
					       	 
    http.send(null);
    updateMenu(url);
   
    
    
  }
}
function submitSearch(param){
  if(!isWorking){
     var url = homeURL.replace("#./","")+param; 
    
    var stateObj = { ajax: "ajax", url: url };
    window.History.pushState(stateObj, "",url);
   
    http.open('GET',url,true);
    isWorking=true;
    http.onreadystatechange=showPage;
    http.send(null);
     
  
  }
}

function getContent(txt,itemId){
	
			var content = txt;
			if(content.indexOf('id="'+itemId+'"') < 0) return "";
			
	    content = content.split('id="'+itemId+'"')[1];
      content = content.substring(content.indexOf('>')+1);
      var depth=1;
      var output='';
      var cat = false;
      while(depth>0){
      	
      	if(cat)
      		output+='</div>';
      		cat = true;
        temp = content.split('</div>')[0];
        //count occurrences
        i=0;
        pos = temp.indexOf("<div");
        while(pos!=-1){
          i++;
          pos = temp.indexOf("<div",pos+1);
        }
        //end count
        depth=depth+i-1;
        output=output+content.split('</div>')[0];
        content = content.substring(content.indexOf('</div>')+6);
      }
      
      return output;
      
}

function sameSidebars(sidebar,selector){
	
	var sidebarIds = [];
	var sidebarCount = 0;
	jQuery(selector).children("aside").each(function(){
			sidebarIds[""+this.id] = ""+this.id;
			sidebarCount++;
	});
	
	
	var regexp = new RegExp('id="([^"]+)"');
	var txt = sidebar;
	var pos = txt.indexOf("<aside");
	var same = true;
	var sameCount = 0;
	while(pos!=-1 && same){
          i++;
          var end = txt.indexOf(">",pos+1);
          var aside = txt.substring(pos,end);
          var ids = regexp.exec(aside);
          if(ids.length>1){
          	same = same && sidebarIds[""+ids[1]] && sidebarIds[""+ids[1]]==ids[1];
          }
          
          txt = txt.substring(end);
          pos = txt.indexOf("<aside");
          sameCount++;
  }

	return same && sidebarCount == sameCount;
	
	
}

function sameImportant(important,selector){
	
	var postsIds = [];
	var postCount = 0;
	jQuery(selector).find("article").each(function(){
			postsIds[""+this.id] = ""+this.id;
			postCount++;
	});
	
	
	var regexp = new RegExp('id="([^"]+)"');
	var txt = important;
	var pos = txt.indexOf("<article");
	var same = true;
	var sameCount = 0;
	while(pos!=-1 && same){
          i++;
          var end = txt.indexOf(">",pos+1);
          var aside = txt.substring(pos,end);
          var ids = regexp.exec(aside);
          if(ids.length>1){
          	same = same && postsIds[""+ids[1]] && postsIds[""+ids[1]]==ids[1];
          }
          
          txt = txt.substring(end);
          pos = txt.indexOf("<article");
          sameCount++;
  }

	return same && postCount == sameCount;
	
	
}
     
function getTitle(txt){
	var pos = txt.indexOf("<title>");
	var res =  txt.substring(pos+"<title>".length,txt.indexOf("</title>"));
	var decoded = jQuery("<div/>").html(res).text();	
	return decoded;
	
}

function getBodyCls(txt){
	var pos = txt.indexOf("<body");
	pos = txt.indexOf('class="',pos+'<body'.length);
	var res =  txt.substring(pos+'class="'.length,txt.indexOf('"',pos+'class="'.length+1));
	return res;
}

function showPage(){
  if(http.readyState==4){
    isWorking=false;
    
    if(http.status>0){
      
     // MUY IMPORTANTE: Obtener los contenidos
     
     var title = getTitle(http.responseText);
     var content = getContent(http.responseText,"content");
     var secondarySidebar = getContent(http.responseText,"secondary2");
     var contentImportant = getContent(http.responseText,"content-important");
     var bodyClass = getBodyCls(http.responseText);
      
      
     if(bodyClass.indexOf("home")<0){
         
              jQuery("#content-important").fadeOut(300);
         
     }else{
     	  if(jQuery("#content-important").length>0){
     	 			if(!sameImportant(contentImportant,"#content-important")){
		     		  jQuery("#content-important").fadeOut(300,function(){
					     		jQuery("#content-important")[0].innerHTML = contentImportant;
					     		jQuery("#content-important").fadeIn(300);
					     	});
					  }else{
		        	 	jQuery("#content-important").fadeIn(300);
					  }
      	}else{
      		jQuery("#primary").before('<div id="content-important" role="main-important"></div>');
      		jQuery("#content-important").toggle();
      		jQuery("#content-important").html(contentImportant);
      		jQuery("#content-important").fadeIn(300);
      	
      	}
         
     }
      
      // MUY IMPORTANTE: Actualizar capas en este orden
    
  	 jQuery("#secondary2").fadeOut(300,function(){
  	 		jQuery("#secondary2")[0].innerHTML = secondarySidebar;
  	});
				
			jQuery("#comments-loader").fadeOut(300,function(){
	     jQuery("#comments-loader")[0].innerHTML = "";
	   });
   
    if(content.indexOf("fancy_notification")>=0){
    	jQuery("#fancy_notification").remove();
    }
     jQuery("#content").fadeOut(300,function(){
     	
     		jQuery("body").attr("class",bodyClass);
     		
	     	document.title = title;
	      
      	jQuery("#content")[0].innerHTML = content;
      	
      	if(bodyClass.indexOf("wpsc")<0 && bodyClass.indexOf("product-categories")<0){
      			jQuery("#secondary2").fadeIn(300);
      	}
	      	
	      	
      	jQuery("#content").fadeIn(300,function(){
      		
		      	 callbacksInit();
		      	 
		      	 	if(jQuery("#fancy_notification").length>0)
													jQuery("#fancy_notification").appendTo(jQuery("body")[0]); 			
													
													
		      	 if(jQuery('#nav-below a:first').length>0){
		      	   
				      	 	var path = jQuery('#nav-below a:first').attr('href');
				      	 	if(path.indexOf("page/")){
				      	 		path = path.substring(0,path.indexOf("page/"))+"page/";
				      	  }else{
				      	  	path = path.substring(0,path.indexOf("paged="))+"paged=";
				      	  }
				      	 	if(jQuery('#content').infinitescroll){
				      	 	 																	  
								        var oldIS = jQuery('#content').data("infinitescroll").options;
								        var newIS = {debug : false,
																		loading			: oldIS.loading,
																		state			: { currPage	: "1"},
																		nextSelector    : oldIS.nextSelector,
																		navSelector     : oldIS.navSelector,
																		contentSelector : oldIS.contentSelector,
																		itemSelector    : oldIS.itemSelector,
																		pathParse		: [path, ""],
																		pixelsFromNavToBottom : jQuery(document).height() - jQuery('#nav-below a:first').offset().top,
																		path: [path]
																		};
												
												jQuery(newIS.loading.msg).find("div").html(newIS.loading.msgText);
												jQuery(newIS.loading.msg).find("img").show();
												
												jQuery('#content').infinitescroll(newIS);
												jQuery("#content").data("infinitescroll").options.state = { currPage	: "1"};
											  jQuery('#content').data("infinitescroll").bind();
												 
											
												
					       	 }
					       	 
					       	 
			       }else{
			         if(jQuery('#content').infinitescroll){
		      	   	jQuery('#content').infinitescroll({pixelsFromNavToBottom : -999999});
		      	  }
			       }
			       
			        var txt = jQuery("#content .entry-content").text().substring(0,200);
			        
			       
			       	WPCSwitcher.GraphStreamPublish.Body = WPCSwitcher.GraphStreamPublishApp.Body = {message: 'comentó en ' + window.title,
				 			link: window.location,
				 			name: window.title,
				 			caption: window.title,
				 			description: txt.length>200 ? (txt.substring(0,200)+"...") : txt};
													 			
							var state = window.History.getState();
							
							if(state.data.target && state.data.target!="" && state.data.target!="#"){
							   var target_offset = jQuery(state.data.target).offset();
								 var target_top = target_offset.top;
        				 jQuery('html, body').animate({scrollTop:target_top}, 500); 
									
							}else{
			     			scrollTo(400,400);
			     		}
      		});
      	
      	
     	});
    }
  }
}



// this function is for binding actions to events and rebinding them after they are replaced by AJAX
// these functions are bound to events on elements when the page is fully loaded.
jQuery(document).ready(function () {
	
});

