var items = new Array();
var catList = new Array();
var headerRowCount = 1;
var catItemCount = [];

function ItemInfo( catID, catPropID, catPropTermID, termName, propertyName, categoryName, status ) {
    this.catID = catID;
    this.catPropID = catPropID;
    this.catPropTermID = catPropTermID;
    this.termName = termName;
    this.propertyName = propertyName;
    this.categoryName = categoryName;
    this.status = status;
}

function defineItem( catID, catPropID, catPropTermID, termName, propertyName, categoryName, status ) {
	var id = catPropTermID.split("_")[2];
	items[ id ] = new ItemInfo( catID, catPropID, catPropTermID, termName, propertyName, categoryName, status );
}

function catItemInfo(catID, categoryName) {
  this.catID = catID
  this.categoryName = categoryName
}

function defineCat( catID, categoryName ) {
	catList[catID] = new catItemInfo( catID, categoryName );
    catItemCount[catID] = 0;
}

String.prototype.trim = function () {
    return this.replace(/^\s*|\s*$/g,"");
}

function addArbitraryItem() {

    var catID = get("catSelect").options[get("catSelect").selectedIndex].value.split("-")[1].split("_")[0];
    var catPropID = get("catSelect").options[get("catSelect").selectedIndex].value.split("-")[1].split("_")[1];
    var catPropTermID = catID + "_" + catPropID + "_" + catPropID + "11111";
    var termName = get("termOtherVis"+catID+"_"+catPropID).value;
    var propertyName = get("catSelect").options[get("catSelect").selectedIndex].text;
    var categoryName = catList[catID].categoryName;
    var status = "Checked";

    if ( catItemCount[catID] >= 30 ) {
        alert( "You can only select 30 items." );
        return false;
    }

    if ( !termName || termName.trim() == "" ) {
        alert("Please enter a product or service.");
    } else {

        catItemCount[catID]++;

        defineItem( catID, catPropID, catPropTermID, termName, propertyName, categoryName, status );

        displayItems( catID, catID );

        get('termOther'+catID+'_'+catPropID).value = termName;
        get('termOtherTextBox'+catID+"_"+catPropID).style.display = "none";
        get('termOtherStatic'+catID+"_"+catPropID).style.display = "block";
        get('termOtherStatic'+catID+"_"+catPropID).innerHTML = termName;

        get('addButtonDiv'+catPropTermID).style.display = "none";
        get('removeButtonDiv'+catPropTermID).style.display = "block";

    }

}

function toggleArbitraryEntry( thisID, action ) {

    var idParts = thisID.split("_");
    var catID = idParts[0].match( /[^0-9]+([0-9]*)/ )[1];
    var catPropID = idParts[1];
    var catPropTermID = idParts[2];

    var arbitraryFieldName = "termOther" + catID + "_" + catPropID;
    var arbitraryFieldNameVis = "termOtherVis" + catID + "_" + catPropID;

    if ( !action ) {

        items[catPropTermID] = null;
        get(arbitraryFieldName).value = "";
        get(arbitraryFieldNameVis).value = "";

        get('termOtherTextBox'+catID+"_"+catPropID).style.display = "block";
        get('termOtherStatic'+catID+"_"+catPropID).style.display = "none";

        get('addButtonDiv'+catID+"_"+catPropID+"_"+catPropTermID).style.display = "block";
        get('removeButtonDiv'+catID+"_"+catPropID+"_"+catPropTermID).style.display = "none";

    }

}

//---Uncheck Term---
function toggleTerm( thisID, action ) {

	var shortItemID = thisID.split("_")[2];
	var catID = items[ shortItemID ].catID;
	var divID = items[ shortItemID ].catID;

    if ( action && catItemCount[catID] >= 30 ) {
        alert( "You can only select 30 items." );
        return false;
    }

	items[ shortItemID ].status = action ? "Checked" : "Unchecked";

    catItemCount[catID] += 1 * ( action ? 1 : -1 );

	displayItems( catID, divID );

	var targetCheckbox = document.form.elements[thisID] || false;
    if ( targetCheckbox ) {
        if ( action != targetCheckbox.checked ) {
            targetCheckbox.checked = action;
        }
    } else {
        toggleArbitraryEntry( thisID, false );
    }

}

//--Build sub-array of selected rows from Main array----

function getCatItems( catID ) {

   var catItems = new Array();
   var cat;
   var stateOn='Checked';
   var id;
   
   for ( id in items ) {

	//get each row in array
	 
	 cat=items[id];
	

	if ( cat && cat.catID == catID ) {
		if ( cat.status == stateOn ) {
        	catItems[id] = cat;
	    }
     }
	 
   }

   return catItems;

}



//Writes to Div/Layer
function layerWrite(text, divID){
//alert('text '+text);
//alert('div ID target '+divID);
  var x;        
        if (document.getElementById)
        {
                x = document.getElementById(divID);
                x.innerHTML = text;
        }
        else if (document.all)
        {
                x = document.all[divID];
                x.innerHTML = text;
        }
        else if (document.layers)
        {
                x = document.layers[divID];
                x.document.open();
                x.document.write(text);
                x.document.close();
        }
		
		toggleRow (divID, false);
		toggleRow (divID, true);
		
}


function toggleRow ( targetId, action ) {
                    try {
                        get( targetId ).style.display = action ? 'table-row' : 'none';
                    } catch ( ex ) {
                        get( targetId ).style.display = action ? 'block' : 'none';
                    }
         }


	
function preloadImage( imagePath, width, height ) {
    var img = new Image( width, height );
    img.src = imagePath;
    return img;
}
var removeButtonImage = preloadImage( '/images/icon-remove-term.gif', 10, 10 );

function displayItems( catID, divID ) {

  var catItems = getCatItems(catID);

  var catPropTermID;
  var item;
  var itemHTML;
  var catTermCount = 1;

  var itemHTML = '<table width="614" border="0" cellspacing="0" cellpadding="2">';
  
  /*if ( headerRowCount == 1 ) {
  
		itemHTML +='                <tr>';
		itemHTML +='                 <td width="21" height="20" class="selectedHeadStyle">#</td>';
		itemHTML +='                       <td width="171" class="selectedHeadStyle">Category</td>';
		itemHTML +='                       <td width="151" class="selectedHeadStyle">Sub-category</td>';
		itemHTML +='                       <td width="250" class="selectedHeadStyle">Product or service</td>';
		itemHTML +='                       <td width="21" align="right" class="selectedHeadStyle">&nbsp;</td>';
		itemHTML +='                    </tr>';

		headerRowCount++;

	}*/
	
	
	
    for ( catPropTermID in catItems ) {

      item = items[catPropTermID];
	  
	  
//categoryName, propertyName, termName
			
		itemHTML +='                     <tr>';
		itemHTML +='                       <td width="20" class="selectedItemWhite">'+catTermCount+'</td>';
		itemHTML +='                       <td width="170" class="selectedItemWhite">'+item.categoryName+'</td>';
		itemHTML +='                       <td width="150" class="selectedItemWhite">'+item.propertyName+'</td>';
		itemHTML +='                       <td width="250" class="selectedItemWhite">'+item.termName+'</td>';
		itemHTML +='                       <td width="24" align="right" class="selectedItemWhite"><a href="javascript:toggleTerm(\'catPropTerm'+item.catPropTermID+'\', false);"><img src="' + removeButtonImage.src + '" width=10 height=10 border=0></a></td>';
		itemHTML +='                     </tr>';
		
		catTermCount++;


    }

    itemHTML +=  '</table>';
	divID = "divcatID"+ divID;
    
    if ( catItems.length == 0 ) {
		document.getElementById( divID ).style.display = "none";
	} else {
		document.getElementById( divID ).style.display = "block";
	    layerWrite( itemHTML, divID );
	}

}

if (document.layers){
   //Netscape 4 specific code
   pre = 'document.';
   post = '';
}

if (document.getElementById){
   //Netscape 6 specific code
   pre = 'document.getElementById("';
   post = '").style';
}

if (document.all){
   //IE4+ specific code
   pre = 'document.all.';
   post = '.style';
}

function showLayer(lyr){
   eval(pre + lyr + post).display = 'block';
}

function hideLayer(lyr){
   eval(pre + lyr + post).display = 'none';
}

function updateNotesHeight() {
	document.getElementById('notes').style.height = document.getElementById('actions').offsetHeight + 'px';
}

function addRow(id,action,status)
{
	var tbl = document.getElementById('actions');
	var index = tbl.rows.length;
	var row = tbl.insertRow(index);
	
	// number cell
	var numberCell = row.insertCell(0);
	var textNode = document.createTextNode(index+1);
	numberCell.appendChild(textNode);
	numberCell.style.width = '5%';
	
	// action cell	  
	var actionCell = row.insertCell(1);
	var textNode = document.createTextNode(action);
	actionCell.appendChild(textNode);
	actionCell.style.width = '60%';

	// status cell
	var statusCell = row.insertCell(2);
	var sel = document.createElement('select');
	var statuses = new Array('Not Started','In Progress','On Hold','Cancelled','Completed');
	for(x in statuses) {
			sel.options[x] = new Option(statuses[x],statuses[x]);
			if (status == statuses[x]) sel.selectedIndex = x;
	}	
	sel.id = 'status'+index;
	sel.onchange = updateAction;
	statusCell.appendChild(sel);
	statusCell.style.width = '25%';

	// delete cell
	var deleteCell = row.insertCell(3);
	if (sel.selectedIndex == 0) {
		var deleteLink = document.createElement("a");
		var href = "javascript:removeAction("+index+");";
		deleteLink.setAttribute("href", href);
		deleteLink.innerHTML = 'X';	
	} else {
		var deleteLink = document.createTextNode('');
	}
	deleteCell.appendChild(deleteLink);
	deleteCell.style.width = '10%';
	deleteCell.style.textAlign = 'center';
}

function addAction(id,action,status) {
	var exists = false;
	for(x in actionsArray) {
		if (actionsArray[x][0] == id) exists = true;
	}
	if (exists == false) {
		actionsArray[actionsArray.length] = new Array(id,action,status);
	} else {
		alert('Sorry, you cannot add an action more than once.');
	}
	refreshActionsTable();
}

function deleteKey(array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};

function removeAction(index) {
	deleteKey(actionsArray,index);
	actionsArray.sort();
	refreshActionsTable();
}

function updateAction(id,status) {
	for(x in actionsArray) {
		if (document.getElementById('status'+x)) actionsArray[x][2] = document.getElementById('status'+x).options[document.getElementById('status'+x).selectedIndex].value;
	}
	refreshActionsTable();
}

function refreshActionsTable() {
	// Clear table
	var actionsTable = document.getElementById('actions');
	var output = "";
    while(actionsTable.hasChildNodes()) actionsTable.removeChild(actionsTable.firstChild);
	for (i in actionsArray) {
		if (actionsArray[i][0] != '') {
			addRow(actionsArray[i][0],actionsArray[i][1],actionsArray[i][2]);
			output += actionsArray[i][0]+","+actionsArray[i][1]+","+actionsArray[i][2]+"|";
		}
	}
	document.getElementById('updatedActions').value = output;
	updateNotesHeight();
}

var tabsClass = {
	tabSetArray: new Array(),
	classOn: "tab_on",
	classOff: "tab_off",
	addTabs: function (tabsContainer) {
		var tabs = document.getElementById(tabsContainer).getElementsByTagName("a");
		for (x in tabs) {
			if (typeof(tabs[x].id) != "undefined") {
				this.tabSetArray.push(tabs[x].id);
			} else {}
		}
	},
	switchTab: function (element) {
		for (x in this.tabSetArray) {
			tabItem = this.tabSetArray[x];
			dataElement = document.getElementById(tabItem + "_data");
			if (dataElement) {
				if (dataElement.style.display != "none") {
					dataElement.style.display = "none";
				} else {}
			} else {}
		tabElement = document.getElementById(tabItem);
		if (tabElement) {
			if (tabElement.className != this.classOff) {
				tabElement.className = this.classOff;
			} else {}
		} else {}
		}
	document.getElementById(element.id + "_data").style.display = "";
	element.className = this.classOn;
	}
};

function setRegion(region) {
	document.getElementById('region').value = region;
	hideLayer('regionList');
}

function noDoubleSubmit(id) {
	window.setTimeout(function() {
		document.getElementById(id).disabled = true;
	},0);
	return true;
}

function setWindowSize(width,height) {
	if (window.outerWidth) {
		window.outerWidth = width;
		window.outerHeight = height;
	}
	else if (window.resizeTo) {
		window.resizeTo(width,height);
	}
	else {
		// Not supported
	}
	window.moveTo(width/2,height/2);
}

function openWindow(url) {
	window.open (url, "leads","menubar=1,resizable=1,width=350,height=250"); 
}