var active = new Array();
var catArray = new Array(4);
var catArrayValues = new Array(4);
catArray['Mac OS'] = new Array("All", "Audio", "Business", "Developer Tools", "Drivers", "DTP/Prepress", "Educational", "Finance", "Font Tools", "Games", "Graphics", "HTML Tools", "Internet Utilities", "Math/Scientific", "Multimedia", "Network/Admin", "Screensavers", "Security", "System Utilities", "Utilities", "Word Processing");
catArray['PalmOS'] = new Array("All", "Business", "Developer Tools", "Educational", "Finance", "Games", "Graphics", "Internet Utilities", "Math/Scientific", "Network/Admin", "Security", "System Utilities", "Utilities", "Word Processing");
catArray['iPhone'] = new Array("All", "Audio", "Blogs / Forums", "Business", "Calculate / Convert", "Calendar", "Developer Tools", "Email / Messaging", "Food", "Games", "International", "Miscellaneous", "Networking / Security", "News", "Photo", "Radio / Podcasts", "Reference", "Shopping", "Sports", "Travel", "Video");
//catArray['Mac OS X'] = new Array("All", "Audio", "Business", "Developer Tools", "Drivers", "DTP/Prepress", "Educational", "Finance", "Font Tools", "Games", "Graphics", "HTML Tools", "Internet Utilities", "Math/Scientific", "Multimedia", "Network/Admin", "Screensavers", "Security", "System Utilities", "Utilities", "Widgets", "Word Processing");
catArrayValues['Mac OS'] = new Array("all", "audio", "business", "developertools", "drivers", "prepress", "educational", "finance", "fonttools", "games", "graphics", "htmltools", "internetutilities", "mathscientific", "multimedia", "networkadmin", "screensavers", "security", "systemutilities", "utilities", "wordprocessing");
catArrayValues['PalmOS'] = new Array("all", "business", "developertools", "educational", "finance", "games", "graphics", "internetutilities", "mathscientific", "networkadmin", "security", "systemutilities", "utilities", "wordprocessing");
catArrayValues['iPhone'] = new Array("All", "audio", "blogs", "business", "calculate", "calendar", "developertools", "msg", "food", "games", "intl", "misc", "networking", "news", "photo", "podcast", "reference", "shopping", "sports", "travel", "video");
//catArrayValues['Mac OS X'] = new Array("all", "audio", "business", "developertools", "drivers", "prepress", "educational", "finance", "fonttools", "games", "graphics", "htmltools", "internetutilities", "mathscientific", "multimedia", "networkadmin", "screensavers", "security", "systemutilities", "utilities", "widgets", "wordprocessing");

//catArray['Windows'] = new Array("All", "Audio", "Business", "Developer Tools", "Drivers", "DTP/Prepress", "Educational", "Finance", "Font Tools", "Games", "Graphics", "HTML Tools", "Internet Utilities", "Math/Scientific", "Multimedia", "Network/Admin", "Screensavers", "Security", "System Utilities", "Utilities", "Word Processing");
//catArrayValues['Windows'] = new Array("all", "audio", "business", "developertools", "drivers", "prepress", "educational", "finance", "fonttools", "games", "graphics", "htmltools", "internetutilities", "mathscientific", "multimedia", "networkadmin", "screensavers", "security", "systemutilities", "utilities", "wordprocessing");

subCats = new Array('SubCat1','SubCat2','SubCat3','SubCat4');

var d;
var selectedPlatform = 'Mac OS X';
var selectedCategory = 'All';

function updateFromPlatform(platform)
{
    var t = document.getElementById(selectedPlatform);
    t.style['backgroundColor'] = '#fff';
    selectedPlatform = platform;
    t = document.getElementById(selectedPlatform);
    t.style['backgroundColor'] = '#c0d9d9';
    //load products from AJAX

    //load category list
    
    selectedCategory = 'All';
    doUpdateCat(platform);
    updateFromCategory(selectedCategory);
}

function togglePlatform(platform)
{
    if( active[platform + ' '] )
    {
        active[platform + ' '] = false;
        
        for (field in active)
        {
            if(active[field])
            {
                fieldList = field.split('-');
                if(fieldList[0] == platform && fieldList.length >= 2)
                {
                    active[field] = false;
                }
            }
        }
        
    } else {
        active[platform + ' '] = true;
    }
    updateFromPlatform(platform);
    updateFromCategory(selectedCategory);
    updateFilterDisplay();
}

function toggleCategory(category)
{
    
    pieces = category.split('-');
    if(!active[pieces[0] + ' '])
    {
        togglePlatform(pieces[0]);
    }
    
    var t = document.getElementById('marker' + pieces[1]);
    if( active[ category + ' '] )
    {
        t.style['backgroundColor'] = '#9c9';
        active[ category + ' '] = false;
        t.innerHTML = '+';
        
        var removePlatform = true;
        for (field in active)
        {
            if(active[field])
            {
                fieldList = field.split('-');
                if(fieldList[0] == pieces[0] && fieldList[1] == category && fieldList.length == 3)
                {
                   active[field] = false;
                }
                if(fieldList[0] == pieces[0] && fieldList.length == 2)
                {
                   removePlatform = false;
                }
            }
        }
        
        if(removePlatform)
        {
        	active[pieces[0] + ' '] = false;
        }
        
    } else {
        
        if( pieces[1] == 'All' )
        {
			for (field in active)
			{
				if(active[field])
				{
					fieldList = field.split('-');
					if(fieldList[0] == pieces[0] && fieldList.length >= 2)
					{
						active[field] = false;
					}
				}
			}
        } else {
        	active[pieces[0] + '-All '] = false;
        }
        
        t.style['backgroundColor'] = '#c66';
        active[ category + ' '] = true;
        t.innerHTML = '-';
    }
    updateFromPlatform(pieces[0]);
    updateFromCategory(pieces[1]);
    updateFilterDisplay();
}

function toggleSubCategory(subCategory)
{
    
    var t = document.getElementById('marker' + subCategory);
    
    
    if( active[selectedPlatform + '-' + selectedCategory + '-' + subCategory] )
    {
        t.style['backgroundColor'] = '#9c9';
        active[selectedPlatform + '-' + selectedCategory + '-' + subCategory] = false;
        t.innerHTML = '+';
    } else {
        t.style['backgroundColor'] = '#c66';
        active[selectedPlatform + '-' + selectedCategory + '-' + subCategory] = true;
        t.innerHTML = '-';
    }
    
    if(!active[selectedPlatform + ' '])
    {
        togglePlatform(selectedPlatform);
    }
    
    if(!active[selectedPlatform + '-' + selectedCategory + ' '])
    {
        toggleCategory(selectedCategory);
    }
    
    updateFilterDisplay();
}

function showUpdate(list) {
	d = document.getElementById('AJAXData');
	
	//var list = form.updates[form.updates.selectedIndex].value

	if(xmlhttp) {
		xmlhttpdo('/php/AJAX/frontPage.php?function=updatesTable&list=' + list
			+ '&platform=' + CurrentPlatform);
	}
}

function sortTable(field, direction) {
	d = document.getElementById('AJAXData');
	if(xmlhttp) {
		if (xmlhttp.readyState==0 || xmlhttp.readyState==4) 
			{
		xmlhttpdo('/php/AJAX/frontPage.php?function=updatesTable&by=' + field
			+ '&dir=' + direction + '&platform=' + CurrentPlatform);
			}
	}
}

function pageTable(page) {
	d = document.getElementById('AJAXData');
	if(xmlhttp) {
		xmlhttpdo('/php/AJAX/frontPage.php?function=updatesTable&page=' + page
			+ '&platform=' + CurrentPlatform);
	}
	scroll(0,0);
}

function updateFilterDisplay()
{
    var macosxDisplay;
    var macosDisplay;
    var winDisplay;
    var palmDisplay;
    var iphoneDisplay;
    //alert(active[selectedPlatform]);
    macosxDisplay = '';
    macosDisplay = '';
    winDisplay = '';
    palmDisplay = '';
    iphoneDisplay = '';
    
    var num = 0;
    var tmp = new Array();
    var sorted = new Array();
    for (i in active)
    {
        if ( active[i] )
        {
            tmp[num++] = i + "|" + active[i];
        }
    }

    tmp = tmp.sort();
    for (i = 0; i < tmp.length; i++)
    {
        x = tmp[i].split("|")
        sorted[x[0]] = x[1];
    }
    for (all in sorted)
    {
    	var filterDisplay = '';
        x = all.split('-');
        if( x.length == 3 )
        {
            filterDisplay = filterDisplay + '&nbsp;&nbsp;- ' + x[2];
        } else {
            if( x.length == 2 )
            {
                filterDisplay = filterDisplay 
                	+'<a href="javascript:toggleCategory(\'' + all.substring(0,all.length-1) + '\')" class="minus1">-</a>' 
                	+ '&nbsp;- ' + x[1];
            } else {
                filterDisplay = filterDisplay + x[0];
                x[0] = x[0].substring(0,all.length-1);
            }
        }
        filterDisplay = filterDisplay + '<br clear="right" />';
        if(x[0] == 'Mac OS X')
        {
        	macosxDisplay = macosxDisplay + filterDisplay;
        }
        
        if(x[0] == 'Mac OS')
        {
        	macosDisplay = macosDisplay + filterDisplay;
        }
        
        if(x[0] == 'PalmOS')
        {
        	palmDisplay = palmDisplay + filterDisplay;
        }
        
        if(x[0] == 'iPhone')
        {
        	iphoneDisplay = iphoneDisplay + filterDisplay;
        }
        
        if(x[0] == 'Windows')
        {
        	winDisplay = winDisplay + filterDisplay;
        }
    }
    
    
    
    var ratingOptions = '<option value = "0" label = "No Restriction">No Restriction</option>'
    	+ '<option value = "1" label = "1 Star">1 Star</option>'
    	+ '<option value = "2" label = "2 Stars">2 Stars</option>'
    	+ '<option value = "3" label = "3 Stars">3 Stars</option>'
    	+ '<option value = "4" label = "4 Stars">4 Stars</option>'
    	+ '<option value = "5" label = "5 Stars">5 Stars</option>';
    	
    var reviewOptions = '<option value = "0" label = "0 Reviews">0 Reviews</option>'
    	+ '<option value = "1" label = "1 Reviews">1 Reviews</option>'
    	+ '<option value = "2" label = "2 Reviews">2 Reviews</option>'
    	+ '<option value = "3" label = "3 Reviews">3 Reviews</option>'
    	+ '<option value = "4" label = "4 Reviews">4 Reviews</option>'
    	+ '<option value = "5" label = "5 Reviews">5 Reviews</option>';
    
    if( macosxDisplay != '' )
    {
    	showElement('macosxSetting');
    } else {
    	hideElement('macosxSetting');
    }
    if( macosDisplay != '' )
    {
    	showElement('macosSetting');
    } else {
    	hideElement('macosSetting');
    }
    if( palmDisplay != '' )
    {
    	showElement('palmSetting');
    } else {
    	hideElement('palmSetting');
    }

    if(iphoneDisplay != '')
    {
      showElement('iphoneSetting');
    }
    else
    {
      hideElement('iphoneSetting');
    }
    
    if( winDisplay != '' )
    {
    	showElement('winSetting');
    } else {
    	hideElement('winSetting');
    }
    
    var t = document.getElementById('macosxFilter');
    t.innerHTML = macosxDisplay;
    var t = document.getElementById('macosFilter');
    t.innerHTML = macosDisplay;
    var t = document.getElementById('winFilter');
    t.innerHTML = winDisplay;
    var t = document.getElementById('palmFilter');
    t.innerHTML = palmDisplay;
    var t = document.getElementById('iphoneFilter');
    t.innerHTML = iphoneDisplay;
}

function updateFromCategory(category)
{
	var t = document.getElementById(selectedCategory);
	t.style['backgroundColor'] = '#fff';
    selectedCategory = category;
    t = document.getElementById(selectedCategory);
    t.style['backgroundColor'] = '#c0d9d9';

    //doUpdateSubCat();
    
}

//AJAX Functions
function displayPreferences()
{
    d = document.getElementById("ScratchPad");
    
    d.style.width='450px';
    setInner('Loading....');
    
    if(xmlhttp)
    {
        var url = "/php/AJAX/frontPage.php?function=displayPrefForm";
        
        xmlhttp.open("GET", url,true);
		xmlhttp.onreadystatechange=function() 
		{
			if (xmlhttp.readyState==4) 
			{
				setInner(xmlhttp.responseText);
				sortableCallback();
			}
		}
		xmlhttp.send(null);
    }
    
    showElementPositioned('ScratchPad', -450, 0);

}

function sortableCallback(){
   Sortable.create("firstlist",
     {dropOnEmpty:true,containment:["firstlist","secondlist"],constraint:false});
   Sortable.create("secondlist",
     {dropOnEmpty:true,containment:["firstlist","secondlist"],constraint:false,only:'moveable'});
}

// used for front page popin
function setProDisplayPref(prefForm)
{
	var selectedString =  Sortable.serialize('secondlist')
	var lines = prefForm.linesPerUpdate[0].checked ? 1 : 2 ;
	var mode = prefForm.updateQuantity[0].checked ? 'updates' : 'days';
	var updates = prefForm.updatesPerPage.value;
	var days = prefForm.daysPerPage.value;
	d = document.getElementById('ScratchPad');
	setInner("Loading New Updates Table");
	d = document.getElementById('AJAXData');
	
	var url = '/php/AJAX/frontPage.php?function=saveDisplayPref&lines=' + lines + "&days=" + days + "&platform=" + CurrentPlatform + "&" + selectedString + "&updates=" + updates + "&mode=" + mode;
	xmlhttp.open("GET", url,true);
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4)
		{
			window.location.reload();
		}
	}
	xmlhttp.send(null);
	hideElement('ScratchPad');
}

function getSelectedFields()
{
    var selectedList = document.getElementById("selectedOptions");
    var selectedString;
    var len = selectedList.length -1;
    var selectedArray = new Array(len);
    for(i=len; i>=0; i--){
        selectedArray[i] = selectedList.item(i).value;
    }
	selectedString = selectedArray.join(',');
	return selectedString;
}


//Functions for dynamic tables
function doUpdateCat(n) 
{ 
    var useArray = n; //windows
    
    var c = document.getElementById('catList');
    var labs = catArray[useArray];
    var vals = catArrayValues[useArray];
    var toInner = '<ul>';
    
    for (var i=0;i<labs.length;i++)
    { 
        toInner = toInner + '<li id="' + labs[i] + '" onclick = "updateFromCategory(\'' + labs[i] + '\')">';
        if(active[selectedPlatform + '-' + labs[i] + ' '])
        {
            toInner = toInner + '<a href="javascript:toggleCategory(\'' + selectedPlatform + '-' + labs[i] + '\')" class="minus" id="marker' + labs[i] + '">-</a>';
        } else {
            toInner = toInner + '<a href="javascript:toggleCategory(\'' + selectedPlatform + '-' + labs[i] + '\')" class="plus" id="marker' + labs[i] + '">+</a>';
        }
        toInner = toInner + labs[i] + '</li>';
    }
    toInner = toInner + '</ul>';
    c.innerHTML = '';
    c.innerHTML = toInner;
} 

function doUpdateSubCat(n) 
{ 
    var useArray = n; //windows
    
    var c = document.getElementById('subCatList');
    var labs = subCats;
    var vals = subCats;
    var toInner = '<ul>';
    
    for (var i=0;i<labs.length;i++)
    {         
        toInner = toInner + '<li id = "' + labs[i] + '">';
        if(active[selectedPlatform + '-' + selectedCategory + '-' + labs[i]])
        {
            toInner = toInner + '<a href="javascript:toggleSubCategory(\'' + labs[i] + '\')" class="minus" id="marker' + labs[i] + '">-</a>';
        } else {
            toInner = toInner + '<a href="javascript:toggleSubCategory(\'' + labs[i] + '\')" class="plus" id="marker' + labs[i] + '">+</a>';
        }
        toInner = toInner + labs[i] + '</li>';

    }
    toInner = toInner + '</ul>';
    c.innerHTML = '';
    c.innerHTML = toInner;
} 

function saveSelectionFilter(formFields)
{
	var filterString = '';
    var xmlFields = '';
	var formElements = formFields.elements; 
	for (selected in active)
    {
    	if(active[selected])
    	{
    		filterString = filterString + ',' + encodeURIComponent(selected);
    	}
    }
	for (var i=0;i<formFields.length;i++) 
	{
		if( formElements[i].type == 'checkbox' || formElements[i].type == 'radio')
		{
			if( formElements[i].checked )
			{
				xmlFields = xmlFields + '&' + formElements[i].name + '=' + encodeURIComponent(formElements[i].value);
			}
		}
		else
		{
			if( formElements[i].value != '' )
			{
				xmlFields = xmlFields + '&' + formElements[i].name + '=' + encodeURIComponent(formElements[i].value);
			}
		}
	}
    
    d = document.getElementById('AJAXData');

	if(xmlhttp && (xmlhttp.readyState==4 || xmlhttp.readyState==0) ) {
		xmlhttpdo('/php/AJAX/frontPage.php?function=saveSelectionFilter&filter=' + filterString.substring(1) + xmlFields );
	}
}

var selectedList;
var availableList;

function delAttribute(){
    availableList = document.getElementById("availableOptions");
    selectedList = document.getElementById("selectedOptions");
   var selIndex = selectedList.selectedIndex;
   if(selIndex < 0)
      return;
   availableList.appendChild(
      selectedList.options.item(selIndex))
   selectNone(selectedList,availableList);
}
function addAttribute(){
    availableList = document.getElementById("availableOptions");
    selectedList = document.getElementById("selectedOptions");
   var addIndex = availableList.selectedIndex;
   if(addIndex < 0)
      return;
   selectedList.appendChild( 
      availableList.options.item(addIndex));
   selectNone(selectedList,availableList);
}

function setTop(top){
        document.getElementById
      ('someLayer').style.top = top;
}
function setLayerTop(lyr,top){
        lyr.style.top = top;
}

function selectNone(list1,list2){
    list1.selectedIndex = -1;
    list2.selectedIndex = -1;
    addIndex = -1;
    selIndex = -1;
}

function delAll(){
    var len = selectedList.length -1;
    for(i=len; i>=0; i--){
        availableList.appendChild(selectedList.item(i));
    }
    selectNone(selectedList,availableList);
}

function addAll(){
    var len = availableList.length -1;
    for(i=len; i>=0; i--){
        selectedList.appendChild(availableList.item(i));
    }
    selectNone(selectedList,availableList);
}
