detect = navigator.userAgent.toLowerCase();

$().ready(function(){
	intUpdateCart();
	setInterval("checkAnchor()", 500);
	HASHfix();
	if(detect.indexOf("msie")>-1) {
		newLoc = document.location.toString();
		newLoc = newLoc.replace("http://"+document.domain+"/","");
		if(!newLoc || newLoc == "" || newLoc == "/") newLoc = "home";
		newLoc = '!'+newLoc;
		makeNewHash(newLoc);
	}
});

var currentAnchor = originalAnchor = splitAnchor = '';
var hist_str = ',';
var hist_ind = 0;
var hist_flg = false;
var req = null;
var authRedirect = "";
var sessionRedirect = false;
var loginAction = "/users/signin";

if(document.location == "http://"+document.domain+loginAction){
	sessionRedirect = true;
}

function checkAnchor(){
	if(originalAnchor != document.location.hash){
		originalAnchor = splitAnchor = document.location.hash;
		splitAnchor = splitAnchor.split('!');  //splitAnchor.replace('!','');
		if (splitAnchor[1] == '' || splitAnchor[1] == undefined) {
			currentAnchor = splitAnchor[0];
		}else {
			currentAnchor = splitAnchor[1];
		}
		
		if(splitAnchor.length > 2) {
			callref('/'+splitAnchor[splitAnchor.length-1]);
			return;
		}
		
		var query;
		var fixIE;
		var divID = 'container';

		if(!currentAnchor || currentAnchor == '') {
			query = document.location.toString();
			query = query.replace("http://"+document.domain,"");
			if(query == "" || query == "/") query = "/home";
			fixIE = query.substr(1);
		} else {
			spltDiv = currentAnchor.split('@');
			if (spltDiv[1] == '' || spltDiv[1] == undefined) {
				divID = 'container';
				fixIE = spltDiv[0].replace('#','');
			} else {
				divID = spltDiv[1];
				fixIE = spltDiv[0].replace('#','') + '@' + spltDiv[1];
			}
			query = '/' + spltDiv[0].replace('#','');
		}

		if(detect.indexOf("msie")>-1) {
			if(!hist_flg) {
				fixIE = '!'+fixIE;
				makeNewHash(fixIE);
			} else {
				hist_flg = false;
			}
		}
		callAjaxReq(query,divID);
	}
}

function callAjaxReq(query,divID) {
	
	$('#loader').html("<img src='/img/s/ajaxLoader.gif'>");
	$('#err_msg').hide();$('#flash_msg').hide();
	
	if (req != null) {
		req.abort();
	}
	
	req = $.ajax({url: query,cache:true,
			success: function(data) {
				pageTracker._trackPageview(query);
				$('#'+divID).html(data);
				HASHfix();
				$('.nyroModal').nyroModal();
				$('#loader').html("");
				putHistory(query);
				if(tinyAuthUpdate == true) {
					tinyUpdate(tinyAuthRedirect);
					tinyAuthRedirect = "";
					tinyAuthUpdate = false;
				}
			},
			error: function(data){
				$('#loader').html("");
				switch(data.status){
				case 403 : 
					authRedirect = '/'+currentAnchor;
					callref(loginAction); 
					break;
				default: 
					$('#err_msg').show();
					$('#err_msg').html("Sorry, unable to process. try again!");
				}
				
			}
	});
}

//add to history bar
function putHistory(link){
	//alert(history.length);
	lnk = link.substring(link.lastIndexOf("/")+1,link.length);
	if(!isNaN(parseInt(lnk)))
	lnk = location.hash.substring(location.hash.indexOf('!')+1,location.hash.indexOf('/'));
	$('#history ul li ul').prepend("<li><a href='"+location+"'>"+lnk+"</a></li>");
	$('#history ul li ul li').each(function(ind,ele){
		if(ind>9){$(ele).remove();}		
	});
}

function HASHfix(){
	var links = document.getElementsByTagName("A");
	for(var i=0; i<links.length; i++) {
		var href = links[i].getAttribute("href");
		if (href != '' && href != undefined) {
			if (href.indexOf("hash=") > -1) {
				var hash = href.substr(href.indexOf("hash=") + 5);
				splitAt = hash.split('@')
				links[i].setAttribute("href", "/" + splitAt[0]);
				links[i].onclick = function() {
					callref(this.getAttribute("href"));
					return false;
		        };
			}
			if (href == "#") {
				links[i].setAttribute("href", "javascript:void(0);");
			}
		} else {
			links[i].setAttribute("href", "javascript:void(0);");
		}
		if (links[i].className.match("mkit")) {
			links[i].onclick = function() {
				callref(this.getAttribute("href"));
				return false;
			};
		}
		if (links[i].className.match("tinyMkit")) {
			links[i].onclick = function() {
				tinyUpdate(this.getAttribute("href"),false);
				return false;
			};
		}
		if (links[i].className.match("mkitReload")) {
			links[i].onclick = function() {
				tinyUpdate(this.getAttribute("href"),true);
				return false;
			};
		}
	}
}

function onFrameLoaded(hash,id) {
	if (hist_str.indexOf(","+id+",") > -1) {
		location.hash = hash;
		hist_flg = true;
	} else {
		hist_str = hist_str + id + "," 
	}
}

function makeNewHash(hash) {
    var doc = document.getElementById("hist_frm").contentWindow.document;
    doc.open("javascript:'<html></html>'");
    doc.write("<html><head><scri" + "pt type=\"text/javascript\">parent.onFrameLoaded('"+ hash + "',"+ (hist_ind++) +");</scri" + "pt></head><body>"+hash+"</body></html>");
    doc.close();
}

function callref(hash) {
	//alert(hash)
	hash = hash.replace("http://" + document.domain,"");
	hash = '!'+hash.substr(1);
	location.hash = hash;
}

var tinyAuthRedirect = "";
var tinyAuthUpdate = false;

function tinyUpdate(url,reload) {
	splitURL = url.split('@');
	if(splitURL.length > 1){
		$('#err_msg').hide();
		$('#'+splitURL[1]).html('<img src="/img/indicator.gif" style="display: block;padding: 6px 2px;text-indent: -9000px;z-index: 1;"/>');
		$('#'+splitURL[1]).show();
		$.ajax({url: splitURL[0], context: document.getElementById(splitURL[1]),
			success: function(data) {
				if(!reload) {
					$(this.context).html(data);
					HASHfix();
					$('.nyroModal').nyroModal();
				} else {
					callAjaxReq('/'+currentAnchor,"container");
				}
			},
			error: function(data){
				switch(data.status){
				case 403 :
					tinyAuthRedirect = url;
					authRedirect = '/'+currentAnchor;
					callref(loginAction); 
					break;
				default: 
					$('#err_msg').show();
					$('#err_msg').html("Opps! something went wrong.");
				}
			}
		});
	} else {
		alert("Opps! something went wrong.");
	}
}

var bgReq = null;
var bgCurLoginStatus = false;
var bgOldLoginStatus = null;

function intUpdateCart() {
	if (bgReq != null) {
		bgReq.abort();
	}
	bgReq = $.ajax({
				url: "/shoppingcarts/s_mini_view",
			    dataType: "html",
			    success: function(html) {
					$("#mycart").html(html);
					HASHfix();
					$('.nyroModal').nyroModal();
					setTimeout("intUpdateCart()",10000);
			    },error: function(){
					//alert('opps! unable to update cart');
			    	setTimeout("intUpdateCart()",10000);
			    }
			});
}

function resetCart(phpstr) {
	var rc_id = "";
	$("[id^='cart_']").each(function(index){
		if($(this).html().match(/Remove from cart/ig) ){
			rc_id = $(this).attr("id");
			if(phpstr.indexOf(","+rc_id+",") < 0) {
				$("#"+rc_id+" a").html($("#"+rc_id+" a").html().replace('Remove from Cart','Buy MP3'));
				$("#"+rc_id+" a").attr("href",$("#"+rc_id+" a").attr("href").replace('s_remove','s_addtocart'));
				$("#"+rc_id+" a").attr("class","mp3 tinyMkit");
			}
		}
	});
}

