$(document).ready(function(){
	fillManufacturer();
	fillSort();
	redirManufacturer();
	redirSort();
});

function fillManufacturer() {
	  var oSelect = $("#manu-select");
	  oSelect[0].options.add(new Option("Select Manufacturer", ""));
	  loc = document.location.href;
	  $.ajax({
		type: "GET",
		url: "/ajax/async-getmanufacturer.php",
		dataType: "json",
		success: function(msg) {
		  $.each(msg, function(i, n) {
			  oSelect[0].options.add(new Option(n.MFName, n.Url));
			  if(loc.indexOf(n.Url) != -1) {
				  oSelect.val(n.Url);
			  }
		  });
	    }
	  });		
}

function redirManufacturer(){
	$("#manu-select").bind("change", function(){
		urlBase = $(this).val();
		if (urlBase){
			document.location.href = "/mail-in-rebates/" + urlBase + "/";
		}
		else {
			document.location.href = "/mail-in-rebates/";
		}
	}); 	
} 

function fillSort() {
	  var oSelect = $("#sort-select");
	  oSelect[0].options.add(new Option("Sort by", ""));
	  oSelect[0].options.add(new Option("Manufacture Name", "mn"));	
	  oSelect[0].options.add(new Option("Newest Rebates", "nr"));
	  oSelect[0].options.add(new Option("Expiration", "ed"));
	  oSelect[0].options.add(new Option("Rebates Amount", "ra"));
	  url = document.location.href;
	  sortIndex = url.indexOf('/sb-');
	  if(sortIndex != -1) {
		sb = url.substring(sortIndex+4, sortIndex+6);  
		oSelect.val(sb);
	  }
}

function redirSort() {
	$("#sort-select").bind("change", function(){
		redir = $(this).val();
		var url = document.location.href; 
		url = url.toLowerCase();
		startPos = url.indexOf('mail-in-rebates');
		pageIndex = url.indexOf('/page-');
		if(pageIndex != -1) {
			base = url.substring(startPos-1, pageIndex+1);
			if (redir == '') {
				document.location.href = base;
			}
			else {
				document.location.href = base + "sb-" + redir + ".html";
			}
		}
		else {
			sortIndex = url.indexOf('/sb-');
		    if(sortIndex != -1) {
		        base = url.substring(startPos-1, sortIndex+1);
				if (redir == '') {
					document.location.href = base;
				}
				else {
					document.location.href = base + "sb-" + redir + ".html";
				}
		    } 
		    else {
		    	leng = url.length;
		    	base = url.substring(startPos-1, leng);
				if (redir == '') {
					document.location.href = base;
				}
				else {
					document.location.href = base + "sb-" + redir + ".html";
				}
		    }
		}
	}); 		
}