var proxy = 'proxy.cfm?u=';
var feed  = 'http://feeds.theplatform.com/ps/JSON/PortalService/2.0/getCategoryList?query=HasReleases&query=IncludeParents&startIndex=1&endIndex=500&field=depth&field=fullTitle&field=hasChildren&field=hasReleases&field=ID&field=parent&field=parentID&field=title&PID='+ setting.pid;
var cssMod= '';
var pseudoCat = [
    {
        'title': 'Featured',
        'fullTitle': 'Featured/Featured',
        'depth': 1,
        'parent': 'Featured',
        'hasChildren': false,
        'hasReleases': true,
        'queryString': 'query=Categories|Featured'
    },
    {
        'title': 'Most Viewed',
        'fullTitle': 'Featured/Most Viewed',
        'depth': 1,
        'parent': 'Featured',
        'hasChildren': false,
        'hasReleases': true,
        'queryString': 'field=requestCount&sortField=requestCount&sortDescending=true'
    },
    {
        'title': 'Top Rated',
        'fullTitle': 'Featured/Top Rated',
        'depth': 1,
        'parent': 'Featured',
        'hasChildren': false,
        'hasReleases': true
    }    
];

if (/*@cc_on!@*/false) {
	// Modifications for IE
	cssMod='IE';
} else if (/Safari/.test(navigator.userAgent)) {
	// Modifications for Safari
	cssMod='Safari';
} else if (/Firefox/.test(navigator.userAgent)) {
	cssMod='Firefox';
}

Event.observe(window, 'load', function() { init(0) });

function init(callback) {
	if (callback==1) {
		buildCategories();
		menuCleanup();
		multiColumn();
		modifyCSS();
	} else {
		getMenuData();
	}
}

function modifyCSS() {
	switch (cssMod) {
		case 'IE':
			$A($('menu').getElementsByClassName('depth0')).each(function(el) { el.style.top = '31px'; });
			$A($$('.topItem')).each(function(el) { el.style.marginTop = '-163px'; });
			break;
		case 'Safari':
			$A($$('div#menu div.depth0 ul')).each(function(el) { el.style.backgroundColor = '#6993c5'; });
			$A($$('div#menu div.depth0 ul li')).each(function(el) { el.style.backgroundColor = '#6993c5'; });
			$A($$('div#menu div.depth1 ul')).each(function(el) { el.style.backgroundColor = '#a3b9d1'; });
			$A($$('div#menu div.depth1 ul li')).each(function(el) { el.style.backgroundColor = '#a3b9d1'; });
			$A($('menu').getElementsByClassName('depth0')).each(function(el) { el.style.top = '31px'; });
			$A($$('.topItem')).each(function(el) { el.style.marginTop = '-163px'; });
			break;
		case 'Firefox':
			$A($$('div#menu div.depth0 ul')).each(function(el) { el.style.backgroundColor = '#6993c5'; });
			$A($$('div#menu div.depth0 ul li')).each(function(el) { el.style.backgroundColor = '#6993c5'; });
			$A($$('div#menu div.depth1 ul')).each(function(el) { el.style.backgroundColor = '#a3b9d1'; });
			$A($$('div#menu div.depth1 ul li')).each(function(el) { el.style.backgroundColor = '#a3b9d1'; });
			break;
		default: break;
	}
}

var catData = {};
function getMenuData() {
	var url = proxy+escape(feed);
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			catData = transport.responseText.evalJSON(true);

			var parentID = 0;
			for(var i=0; i<catData.items.length; i++) {
			    var el = catData.items[i];
			    if (el.title == 'Featured') {
			        el.title = "Popular";
			        //el.fullTitle = "Popular";
			        parentID = el.ID;
			        break;
			    }
			}
			
            catData.items = catData.items.concat(pseudoCat);			
			    
			catData.listInfo.itemCount = catData.listInfo.itemCount + pseudoCat.length;
            catData.listInfo.totalCount = catData.listInfo.totalCount + pseudoCat.length;
			
			init(1);
		}
	});
}
function menuCleanup() {
	$A($$('.hasChildren')).each(function(el) {
		if (el.parentNode.getElementsByTagName('li').length==0) {
			$(el).removeClassName('hasChildren');
		}
	});
}
function multiColumn() {
	$A($$('.depth0')).each(function(div) {
		$A($(div).immediateDescendants()).each(function(ul) {
			var liCnt = $(ul).immediateDescendants().size(); 
			if (liCnt < 10) return;
			$A($(ul).immediateDescendants()).each(function(li,i) {
				$(li).addClassName('listCol'+ Math.floor(i/9));
				if ((i/9)==0 || /\./.test((i/9).toString())) return;
				$(li).addClassName('topItem');
			});
		});
	});
}
function buildCategories() {
	var currentUL = $('categories');

	catData.items.each(function(set,i) {
		if (set.parent=='') {
			currentUL = $('categories');
		} else {
			currentUL = $(cleanParentID(set.parent)).getElementsByTagName('ul')[0];
		}
		var li = createLI(set.title,currentUL,set.fullTitle);
		var span = li.getElementsByTagName('span')[0];
		
		if (set.hasChildren) {
			var div = li.appendChild(document.createElement('div'));
				$(div).appendChild(document.createElement('ul'));
				$(div).addClassName('depth'+set.depth);
				$(div).hide();
			$(span).addClassName('hasChildren');
		}
		
		if (currentUL.id=='categories') {
			$(span).addClassName('topCat');
		} else if (set.hasChildren) {
			$(span).addClassName('subCat');
		} else {
			$(span).addClassName('nonCat');
		}
		$(span).setAttribute('rel',i);
		
		if (set.queryString) {
            $(span).observe('click', function() {
                refreshBrowseCategory(null, '', null, null, null, [set.queryString]);
                hideSets(['.depth1','.depth0']);
            });
		} else if (set.title == 'Top Rated') {
	        $(span).observe('click', function() {
	            browseTopRated();
	            hideSets(['.depth1','.depth0']);
	        });		        
		} else {
    		$(span).observe('click', function() {
    			browseCat(catData.items[parseInt(this.getAttribute('rel'),10)].fullTitle);
    			hideSets(['.depth1','.depth0']);
    		});
		}
	});
	$$('.topCat').each(function(el) {
		el.observe('mouseover', function() {
			hideSets(['.depth1','.depth0']);
			window.clearTimeout(mT.depth0.timer);
			mT.depth0.mO = false;
			displayChild(this);
		});
		el.observe('mouseout', function() {
			mT.depth0.timer = window.setTimeout("hideSets(['.depth1','.depth0'],'mT')",500);
			mT.depth0.mO = false;
		});
	});
	$$('.subCat').each(function(el) {
		el.observe('mouseover', function() {
			window.clearTimeout(mT.depth1.timer);
			if (!this.parentNode.parentNode.parentNode.hasClassName('depth1')) {
			    hideSets(['.depth1', '.depth2']);
			}
			displayChild(this);
		});
	});
	$$('.depth1').each(function(el) {
		el.observe('mouseover', function() {
			window.clearTimeout(mT.depth1.timer);
			mT.depth1.mO = true;
		});
		el.observe('mouseout', function() {
			mT.depth1.timer = window.setTimeout("hideSets(['.depth2', '.depth1'],'mT')",1000);
			mT.depth1.mO = false;
		});
	});
	$$('.depth0').each(function(el) {
		el.observe('mouseover', function() {
			window.clearTimeout(mT.depth0.timer);
			mT.depth0.mO = true;
		});
		el.observe('mouseout', function() {
			mT.depth0.timer = window.setTimeout("hideSets(['.depth2','.depth1','.depth0'],'mT')",1000);
			mT.depth0.mO = false;
		});
		$A(el.getElementsByTagName('ul')).each(function(ul) {
			$A($(ul).immediateDescendants()).each(function(li) {
				var span = $(li).getElementsByTagName('span')[0];
				if (!$(span).hasClassName('nonCat')) return;
				if (!$(span).parentNode.parentNode.parentNode.hasClassName('depth0')) return;
				$(span).observe('mouseover', function() {
					window.clearTimeout(mT.depth1.timer);
					hideSets(['.depth2', '.depth1']);
				});
			});
		});
	});
}

// Mouse Tracker
var mT = {
	'depth0': { 'mO': false, 'timer': null },
	'depth1': { 'mO': false, 'timer': null }
};

function displayChild(el) {
	if (!$(el).parentNode.getElementsByTagName('div')[0]) return;
	if (!$(el).hasClassName('hasChildren')) return;
	$(el).parentNode.makePositioned();
	$(el).parentNode.getElementsByTagName('div')[0].show();
}

function hideSets(classes,clr) {
	if (!classes) return;
	if (clr=='mT' && mT.depth1.mO==true) return;
	classes.each(function(set) {
		$$(set).each(function(el) {
			el.hide();
			if (el.hasClassName('depth1')) $(el.parentNode).undoPositioned();
		});
	});
}

function createLI(text,parent,fullTitle) {
	var li = document.createElement('li');
		li.setAttribute('id',cleanParentID(fullTitle));
	var sp = document.createElement('span');
		sp.appendChild(document.createTextNode(text.replace(/\s/g,'\u00a0')));
	li.appendChild(sp);
	
	if (parent.getAttribute('id')=='categories' && setting.menuOrder) { 
		var lastBefore = -1;
		$A($(parent).immediateDescendants()).reverse().each(function(el) {
			var id = el.getAttribute('id').split(':')[1];
			lastBefore = (setting.menuOrder.isBefore(text,id)) ? id : lastBefore;
		});
		if (lastBefore==-1) {
			parent.appendChild(li);
		} else {
			parent.insertBefore(li,$('c:'+ lastBefore));
		}
	} else {
		parent.appendChild(li);
	}
	return li;
}
function cleanParentID(txt) {
	return 'c:'+(txt.replace(/\//g,'_').replace(/\s/g,''));
}

Object.extend(Array.prototype, {
	isBefore: function(a,b) {
		return (this.indexOf(a) < this.indexOf(b));
	}	
});

