// JavaScript Document

var numberOfFields=0;
//contains references to all lists of products
var productLists = new Tables();
var categories = new Categories();

//should downloading div be displayed
var downloading = 0;

//browser sniffer
var bName = navigator.appName;

var pageX=0;
var pageY=0;

var motherboards;
var cpus;

var today = new Date();
var table = document.getElementById("idTable");


//adds required fields
//for configurator
function BasicFields()
{
    table = document.getElementById("idTable");
    
    var row = table.insertRow(0);
    var cell = row.insertCell(0);
    cell.innerHTML = "Kategorija";
    cell.className = "tdHeading Category";
    var cell = row.insertCell(1);
    cell.innerHTML = "Komponenta";
    cell.className = "tdHeading Item";
    var cell = row.insertCell(2);
    cell.innerHTML = "Opis";
    cell.className = "tdHeading Description";
    var cell = row.insertCell(3);
    cell.innerHTML = "Cena";
    cell.className = "tdHeading Price";
    var cell = row.insertCell(4);
    cell.className = "tdHeading Delete";
    cell.innerHTML = "Izbriši";
    
    document.getElementById("idForm").style.display = "none";
    document.getElementById("idDownloading").style.display = "block";
    
	AddFields();
	document.getElementById("idCategory1").selectedIndex = 2;
	document.getElementById("idCategory1").onchange();
	document.getElementById("idCategory1").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete1"));
	
	AddFields();
	document.getElementById("idCategory2").selectedIndex = 1;
	document.getElementById("idCategory2").onchange();
	document.getElementById("idCategory2").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete2"));
	
	//reference to cpu field - necessary for compatibility checking between cpu and mb
	cpus = document.getElementById("idItem2");
		
	AddFields();
	document.getElementById("idCategory3").selectedIndex = 2;
	document.getElementById("idCategory3").onchange();
	document.getElementById("idCategory3").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete3"));
	
	AddFields();
	document.getElementById("idCategory4").selectedIndex = 3;
	document.getElementById("idCategory4").onchange();
	document.getElementById("idCategory4").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete4"));
	
	AddFields();
	document.getElementById("idCategory5").selectedIndex = 8;
	document.getElementById("idCategory5").onchange();
	document.getElementById("idCategory5").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete5"));
	
	AddFields();
	document.getElementById("idCategory6").selectedIndex = 12;
	document.getElementById("idCategory6").onchange();
	document.getElementById("idCategory6").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete5"));
	
	AddFields();
	document.getElementById("idCategory7").selectedIndex = 7;
	document.getElementById("idCategory7").onchange();
	document.getElementById("idCategory7").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete5"));
	
	AddFields();
	document.getElementById("idCategory8").selectedIndex = 9;
	document.getElementById("idCategory8").onchange();
	document.getElementById("idCategory8").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete5"));
	
	AddFields();
	document.getElementById("idCategory9").selectedIndex = 8;
	document.getElementById("idCategory9").onchange();
	document.getElementById("idCategory9").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete5"));
	
	
	AddFields();
	document.getElementById("idCategory10").selectedIndex = 5;
	document.getElementById("idCategory10").onchange();
	document.getElementById("idCategory10").disabled = true;
	//document.getElementById("idAdded").removeChild(document.getElementById("idDelete5"));
	
}

function SetDownloading()
{

    downloading++;
    if(downloading>=5)
    {
    	document.getElementById("idForm").style.display = "block";
        document.getElementById("idDownloading").style.display = "none";
    }
   
}
function initFields()
{
	//set number of optional fields
	numberOfFields = 0;	
}

function AddFields()
{
	//create names 
	numberOfFields++;
	//create row in table of configuration items
	table.insertRow(table.rows.length);
	
	//add fields into table of configuration
	AddFieldCategory();
	AddFieldItem();
	AddFieldInfo();
	AddFieldPrice();
	AddFieldDelete();
	
}

function AddConfigItems()
{
	AddFields();
}

function AddFieldCategory()
{
    //insert cell in row of configuration
    var index = table.rows.length - 1;
    var row = table.rows[index];
    var cell = row.insertCell(0);
    cell.className = "Category";
    
	//create names 
	var nextCategoryId = "idCategory" + numberOfFields;
	var listOfItems = document.getElementById("idAdded");

	//create element in document for categories
	listOfItems.appendChild(document.createElement("p"));
	var category = document.createElement("select");

	//insert into dropdown list categories
	//and set atributes
	categories.AddSubscriber(category);
	category.id = nextCategoryId;
	category.onchange = FillList;
	category.selectedIndex = 0;
	category.text = "";
	//category.className = "";
	
	//listOfItems.appendChild(category);
	cell.appendChild(category);
	
	//slowly appear
	Element.setOpacity(category, 0.0);
	new Effect.Opacity(category, {duration:0.5, from:0.0, to:1.0});
}

function AddFieldItem()
{
    //insert cell in row of configuration
    var index = table.rows.length - 1;
    var row = table.rows[index];
    var cell = row.insertCell(1);
    cell.className = "Item";
    
	//create select element and label
	var nextItemId = "idItem" + numberOfFields;
	var listOfItems = document.getElementById("idAdded");
	var configItem = document.createElement("select");
	configItem.id = nextItemId;
	configItem.onchange = ShowPrice;
	//configItem.onclick = SetInfoUrl;
	configItem.selectedIndex = 0;
	configItem.className = "";
	//listOfItems.appendChild(configItem);
	cell.appendChild(configItem);
	//slowly appear
	Element.setOpacity(configItem, 0.0);
	new Effect.Opacity(configItem, {duration:0.5, from:0.0, to:1.0});

}

function AddFieldPrice()
{
    //insert cell in row of configuration
    var index = table.rows.length - 1;
    var row = table.rows[index];
    var cell = row.insertCell(3);
    cell.className = "Price";
    
	//create price text box
	var nextPriceId = "idPrice" + numberOfFields;
	var listOfItems = document.getElementById("idAdded");	
	var itemPrice = document.createElement("input");
	itemPrice.id = nextPriceId;
	itemPrice.readOnly = true;
	//listOfItems.appendChild(itemPrice);
	cell.appendChild(itemPrice);
	//slowly appear
	Element.setOpacity(itemPrice, 0.0);
	new Effect.Opacity(itemPrice, {duration:0.5, from:0.0, to:1.0});
}

function AddFieldInfo()
{

    //insert cell in row of configuration
    var index = table.rows.length - 1;
    var row = table.rows[index];
    var cell = row.insertCell(2);
    cell.className = "Description";
    
	var listOfItems = document.getElementById("idAdded");
	var image = document.createElement("a");
	var nextImageId = "idInfo" + numberOfFields;
	image.id = nextImageId;
	image.name = "info";
	image.innerHTML = "<img border=\"0\" width=\"16\" height=\"16\" src=\"images/layout/lupa.gif\" >";
	//image.target = "_blank";
	image.target = "_popup";
	image.href = "";
	image.style.visibility = "hidden";
	image.onclick = function(){window.open(image.href, 'popup', "width=640, height=480, location=no, menubar=no,status=no, toolbar=no, scrollbars=no, resizable=no"); return false;}
	//listOfItems.appendChild(image);
	cell.appendChild(image);
	
	//slowly appear
	Element.setOpacity(image, 0.0);
	new Effect.Opacity(image, {duration:0.5, from:0.0, to:1.0});
	
}

function AddFieldDelete()
{
    //insert cell in row of configuration
    var index = table.rows.length - 1;
    var row = table.rows[index];
    var cell = row.insertCell(4);
    cell.className = "Delete";
    
    var listOfItems = document.getElementById("idAdded");
	var del = document.createElement("a");
	var nextImageId = "idDelete" + numberOfFields;
	del.id = nextImageId;
	del.name = "Ukloni";
	del.innerHTML = "<img border=\"0\" src=\"images/layout/remove.gif\" width=\"16\" height=\"16\" >";
	del.href = "#";
	del.onclick = DeleteItem;
	//listOfItems.appendChild(del);
	cell.appendChild(del);
	
	//slowly appear
	Element.setOpacity(del, 0.0);
	new Effect.Opacity(del, {duration:0.5, from:0.0, to:1.0});
	
	/*
	<a href="lastpage.htm">
    <img border="0" src="buttonnext.gif" width="65" height="38">
    </a>
	*/
}

//fills dropdown list
//based on selected category
function FillList()
{
    categories.OnChangeSubscriber(this);
    //if category is not selected
    if(this.options[this.selectedIndex].value==-1)
    {   
        var ind = this.id.replace(/idCategory/, "");
	    var objName = "idItem" + ind;
        ClearDropDown(document.getElementById(objName));
    }
    else
    {
 	    //fills dropdown box
	    ajaxObjectArray[ajaxObjectArray.length] = new ajax();
	    var ajaxIndex = ajaxObjectArray.length-1;
	    var index = this.id;
        
	    ajaxObjectArray[ajaxIndex].queryString = "category=" + this.value + "&today="+today.getDay();
	    ajaxObjectArray[ajaxIndex].requestFile = "productlist.php";
	    ajaxObjectArray[ajaxIndex].onCompletion = function() { SetItems(index, ajaxIndex); };	
	    ajaxObjectArray[ajaxIndex].onError = function() { handleError(ajaxIndex); };
	    ajaxObjectArray[ajaxIndex].onFail = function() { handleFail(ajaxIndex); };
	    ajaxObjectArray[ajaxIndex].initRequest();		// Execute AJAX function	
	}
}


//fills in dropdown box
//with product names
function SetItems(index, ajaxIndex)
{
    SetDownloading();
	//create list of objects with prices and names
	var resp = ajaxObjectArray[ajaxIndex].response;	
	//get combo box needed to be filled in
	var ind = index.replace(/idCategory/, "");
	var objName = "idItem" + ind;
	var object = document.getElementById(objName);
	//empty dropdown box
	ClearDropDown(object);

	//do i have anything in list
	if(resp != "")
	{
		//object.disabled = false;
		var list = eval("(" + resp + ")");
		var itemList = list.list;
		productLists.add(ind-1, itemList);
		
		var opt;
		var listSelection;
		var count = itemList.length;
		var i;
		
		opt = document.createElement("option");
	    opt.text = "Izaberite";
	    opt.value = -1;
	    
        if (bName == "Microsoft Internet Explorer")
        {
	        //add to category
	        object.add(opt);
	    }
	    else
	    {
	        //add to category
	        object.add(opt, null);
	    }
	    
		for(i=0; i<count; i++) 
		{
			//create one of the options in combo
			opt = document.createElement("option");
			opt.text = itemList[i].Item.naziv;
			opt.value = itemList[i].Item.id;
			//var bName = navigator.appName;
			if (bName == "Microsoft Internet Explorer")
			{
				// JavaScript here for IE 4 and later
				//object.add(opt, object.length);
				object.add(opt);
			}
			else if (bName == "Netscape")
			{
			   // JavaScript here for Nav3 and Opera 
			   object.add(opt, null);
			}
			
		}
		object.selectedIndex=0;
		object.onchange();
	}
	else
	{
		//i do not have anything in result list...
		ClearDropDown(object);
		var object1 = document.getElementById("idPrice" + ind);
		object1.value = "";
		//object.disabled = true;
	}
}

function ShowPrice()
{
    //first check set compatibility based on this field
    CheckCompatibility(this);
    //set link for info of this product
    SetInfoUrl(this);
    
    
	var id = this.id;
	var selection = this.selectedIndex;
	var ind = id.replace(/idItem/, "");
	
	var objName = "idPrice" + ind;
	var object = document.getElementById(objName);
	var price = productLists.getPrice((ind-1), this.value);
	object.value = price;
	
	CalculatePrice();
}
	


function ClearDropDown(object)
{
	object.selectedIndex = "";
	var number = object.length;
	for(var i=0; i<number; i++)
	{
		object.selectedIndex = 0;
		object.remove(0);	
	}
	
	    //clear cpu price
    var id = object.id;
    var index = id.replace(/idItem/, "");
    document.getElementById("idPrice"+index).value = "0";
}

function CalculatePrice()
{
	var prices = document.getElementsByTagName("input");
	var price;
	var id;
	var re = /idPrice\d+/;
	var sum=0;
	for(var i=0; i<prices.length; i++)
	{
		price = prices[i];
		id=price.id;
		if(re.test(id))
			if(price.value != "")
				sum += parseInt(price.value);
	}
	document.getElementById("idPrice").value = sum + ",00";
	document.getElementById("idPopust").value = Math.round(sum*0.95) + ",00";
}



function ValidateConfiguration()
{
    var result = true;
    
    if (!document.getElementById)
        result = true; //server side will have to do checking
        
    //check the required components
	var required1 = document.getElementById("idItem1").value;
	var required2 = document.getElementById("idItem2").value;
	var required3 = document.getElementById("idItem3").value;
	var required4 = document.getElementById("idItem4").value;
	var required5 = document.getElementById("idItem5").value;
	
	if(required1 == "" || required2 == "" || required3 == "" || required4 == "" || required5 == "")
	{
	    alert("Za narucivanje konfiguracije moraju da budu izabrane sve obevezne komponente");
	    result = false;
	};
	
    //check if user is logged on
    var userLogged = document.getElementById("idUser").value;
//    if(userLogged == "0")
//    {
//        alert("Niste ulogovani, prvo se ulogujte pa onda napravite konfiguraciju");
//        result = false;
//    }
//    else
//    {
        //check if user already has something in cart
        var cartUsed = document.getElementById("idKorpa").value;
        if(cartUsed == "1")
        {
            var emptyCart = confirm("Vec postoji nesto u korpi. Da li hocete da izbrisemo te stvari?");
            if(emptyCart)
                result = true;
            else
                result = false;    
        }
        else
        {
            //submit configuration list to ordering page
            result = true;
        }
        
//    }
    if(result)
    {
        var numberOfElements = numberOfFields + 1;
        var text = "<div id='korpa-header'>Naručili ste: </div><table class='tbl-korpa-pregled' cellspacing='0' cellpadding='0' border ='0'>"
        //header
        text+="<tr class='even'><td class='popRednibroj'></td><td class='tdHeading popNaziv'>Komponenta</td><td class='tdHeading popKolicina'>Količina</td><td class='tdHeading popCena'>Cena</td></tr>";
        var item;
        var name;
        var price;
        var sorted = CategoriesSort();
        for(var i=0; i<numberOfElements-1; i++)
        {
            item = document.getElementById("idItem"+sorted[i]);
            //if user added fields, but did not choose anything in it
            if(item.options[item.selectedIndex].value != -1)
            {
                if(i%2==0)
                    text += "<tr class='odd'>";
                else 
                    text += "<tr class='even'>";
                text +="<td class='popRednibroj'>";
                text += i+1;
                text +="</td>";
                text +="<td class='popNaziv'>";
                text += item.options[item.selectedIndex].text;
                text += "</td><td class='popKolicina'>1</td>";
                item = document.getElementById("idPrice"+sorted[i]);
                text += "<td class='popCena'>";
                text += item.value;
                text +="</td>";
                text += "</tr>";
            }
        
        }
        item = document.getElementById("idPrice");
		text += "<tr class='odd'><td colspan='4' class='popSuma'><p class='odd'><b>Cena konfiguracije: ";
		text += item.value + "</b></p></td></tr>";
   		text += "</table>";
		
        
        ConfirmConfiguration(text,'ConfirmConfigurationReturnMethod()'); 
        return false;
    }
    else
        return result;
}

function SubmitConfiguration()
{
    var elements = document.getElementsByTagName("select");
    var regExp = /idItem\d+/;
    var configurationString = "";
    configurationString = "napravi=1&loggedIn="+document.getElementById("idUser").value;
    configurationString += "&cartFilled="+document.getElementById("idKorpa").value;
    var number = elements.length;
    var index = 0;
    configurationString +="&items="
    for(var i=0; i<number; i++)
    {
        var element = elements[i];
        var id = element.id;
        if(id.match(regExp))
        {
            //check if user added fields but did not choose anything
            if(element.value != -1)
            {
                if(index > 0)
                    configurationString +="+";
                configurationString +=element.value;
            }
            index++;
        }
    
    }

	ajaxObjectArray[ajaxObjectArray.length] = new ajax();
	var ajaxIndex = ajaxObjectArray.length-1;
	var index = this.id;
	ajaxObjectArray[ajaxIndex].asinch = false;
	ajaxObjectArray[ajaxIndex].queryString = configurationString;
	ajaxObjectArray[ajaxIndex].requestFile = "configurationconfirm.php";
	ajaxObjectArray[ajaxIndex].onCompletion = function() { ConfigurationCreated(ajaxIndex); };	
	ajaxObjectArray[ajaxIndex].onError = function() { handleError(ajaxIndex); };
	ajaxObjectArray[ajaxIndex].onFail = function() { handleFail(ajaxIndex); };
	ajaxObjectArray[ajaxIndex].initRequest();		// Execute AJAX function
    window.location.href = "korpa_pregled.php";
}

function ConfigurationCreated(ajaxIndex)
{
    //alert("Konfiguracija je smestena u korpu.")
    alert(ajaxObjectArray[ajaxIndex].response); 
	window.location.href = "korpa_pregled.php";
}

//checks if processor fits the motherboard
//etc....
function CheckCompatibility(obj)
{
        //get id of categories motherboard and cpu
        var objId = obj.id;
        //check if selected item's category is cpu or motherboard
        var index = objId.replace(/idItem/, "");
        var categoryId = "idCategory"+index;
        var selectedCategory = document.getElementById(categoryId).selectedIndex;
        var categoryItem = productLists.getItem(index-1, obj.options[obj.selectedIndex].value);
        var subCategory;
        if(categoryItem != null)
            subCategory  = categoryItem.grupa;
        //set if other one if this one is AMD or INTEL
        //rule: if MB is AMD, then CPU must be in category AMD       
        regExpIntel = /MB.*INTEL.*/;
        regExpAmd = /MB.*AMD.*/;
        if(subCategory!= null && (subCategory.match(regExpIntel)||subCategory.match(regExpAmd)))
        {
            FilterCpu(subCategory);
        }
}

function FilterCpu(filter)
{
    //determine what should be the filter for cpus
    regExpIntel = /.*INTEL.*/;
    regExpAmd = /.*AMD.*/;
    var regExpCpu;
    if(filter.match(regExpIntel))
        regExpCpu = regExpIntel;
    else    
        regExpCpu = regExpAmd;
    
    var index = parseInt(cpus.id.replace(/idItem/, ""));
    //take category for each cpu and
    //based on regular expression
    //set him to be visible or invisible
    var item;
    ClearDropDown(cpus);

    var itemNumber = productLists.getListLength(index-1);
    var opt;
    opt = document.createElement("option");
	opt.text = "Izaberite";
	opt.value = -1;
    
    if (bName == "Microsoft Internet Explorer")
    {
        //add to category
        cpus.add(opt);
    }
    else
    {
        //add to category
        cpus.add(opt, null);
    }
	    
    for(var i=0; i<itemNumber; i++)
    {
        item=productLists.get(index-1, i)
        if(item.grupa.match(regExpCpu))
        {
            //create one of the options in combo
			opt = document.createElement("option");
			opt.text = item.naziv;
			opt.value = item.id;
			
			if (bName == "Microsoft Internet Explorer")
			{
				// JavaScript here for IE 4 and later
				cpus.add(opt);
			}
			else if (bName == "Netscape")
			{
			   // JavaScript here for Nav3 and Opera 
			   cpus.add(opt, null);
			}
        }
    }    

}

//sets the url for selected product in idItem
function SetInfoUrl(obj)
{
    
    var id = obj.id;
    var index = id.replace(/idItem/, "");
    
    var item = productLists.getItem(index-1, obj.options[obj.selectedIndex].value);
    var infoId = "idInfo"+index;
    var info = document.getElementById(infoId);
    
    info.href = "product_info.php?rid="+obj.value;
    //if inormations for item do not exist disable link
    if(item!= null && item.info=="1")
    {
        info.onclick = function(){return true;};
        info.style.visibility = "";
        Element.setOpacity(info, 0.0);
	    new Effect.Opacity(info, {duration:0.5, from:0.0, to:1.0});
    }
    else
    {
        info.onclick = function(){return false;};        
        info.style.visibility = "hidden";
    }
}

function DeleteItem()
{
    var id = this.id;
    var index = id.replace(/idDelete/, "");
    
    productLists.deleteTable(index-1);
    
    //delete items from DOM specs
    var delCategoryId = "idCategory" + index;
    var delItemId = "idItem" + index;
    var delInfoId = "idInfo" + index;
    var delPriceId = "idPrice" + index;
    //get Nodes
    var delCategory = document.getElementById(delCategoryId);
    var delItem = document.getElementById(delItemId);
    var delInfo = document.getElementById(delInfoId);
    var delPrice = document.getElementById(delPriceId);
    var delDel = this;
    
    //return possibility for this item in categories
    categories.Unsubscribe(delCategory);
    
    //get container
    var listOfItems = document.getElementById("idAdded");
    
    //delete items from DOM specs
    var categoryId = "idCategory" + index;
    var itemId = "idItem" + index;
    var infoId = "idInfo" + index;
    var priceId = "idPrice" + index;
    var delId;
    
    //get Nodes
    var category;
    var item;
    var info;
    var price;
    var del;
    
    //window.setTimeout('DeleteFields('+index+')',1000); 
    //rename all items after deleted one
    for(var i=parseInt(index)+1; i<numberOfFields+1; i++)
    {
        
        categoryId = "idCategory" + i;
        itemId = "idItem" + i;
        infoId = "idInfo" + i;
        priceId = "idPrice" + i; 
        delId = "idDelete" + i;
        
        category = document.getElementById(categoryId);
        item = document.getElementById(itemId);
        info = document.getElementById(infoId);
        price = document.getElementById(priceId);
        del = document.getElementById(delId);
        
        category.id = "idCategory" + (i-1);
        item.id = "idItem" + (i-1);
        info.id = "idInfo" + (i-1);
        price.id = "idPrice" + (i-1); 
        del.id = "idDelete" + (i-1);
    }
    
    numberOfFields--;
    var row = delCategory.parentNode.parentNode;
    row.parentNode.removeChild(row);

    /*
    listOfItems.removeChild(delCategory);
    listOfItems.removeChild(delItem);
    listOfItems.removeChild(delInfo);
    listOfItems.removeChild(delPrice);
    listOfItems.removeChild(delDel);
    */
    
    //calculate price without deleted item
    CalculatePrice();

}


function CategoriesSort() 
{
    var sorted = new Array();
    for(var i=1; i<numberOfFields+1; i++)
        sorted[i-1] = i;

    return sorted;
} 


function Categories()
{
    //whate writes in select fields
    var categoryName = new Array(
    "Procesor",
    "Matična ploča",
    "Kuler",
    "Memorija",
    "Hard disk",
    "CD/DVD/Fdd",
    "Monitor",
    "Modem",
    "Tastatura",
    "Kućište",
    "Multimedia",
    "Zvučnik",
    "Miš",
    "Muzika",
    "Grafika",
    "TV",
    "Softver",
    "Štampač",
    "Skener");
    
    //values that will be sent to ajax request
    var categoryValue = new Array(
    "Cpu",
    "Motherboard",
    "Cooler",
    "Memory",
    "Hdd",
    "Fdd",
    "Monitor",
    "Modem",
    "Keyboard",
    "Case",
    "Multimedia",
    "Speaker",
    "Mouse",
    "Music",
    "Graphic",
    "TV",
    "Software",
    "Printer",
    "Scanner");
    
    //maximum number of occurances in selectedFields
    var numberOfOccurances = new Array(1,1,1,4,4,4,1,1,1,1,5,2,1,1,2,1,10,1,1);
    
    //references to all select fields with categories
    var subscriberRef = new Array();
    
    //adds new subscriber
    this.AddSubscriber = _addSubscriber;
    
    //deletes subscriber
    this.Unsubscribe = _deleteSubscriber;
    
    //when some of the subscirber changes it's property
    this.OnChangeSubscriber = _onChange;
    
    function _addSubscriber(object)
    {
        //add new field in subscriberRef and subscriberSelection
        var newIndex = subscriberRef.length;
        subscriberRef[newIndex] = object;
        //subscriberSelection[newIndex] = -1;
        _fillOptions(object);
	    
    }
    
    //remove subscriber from subscriber list
    function _deleteSubscriber(object)
    {
        //delete subscriber
        var index=-1;
        for(var i=0; i<subscriberRef.length; i++)
        {
            if(subscriberRef[i] == object)
            {
                subscriberRef[i] = null;
                index = i;
            }
        }
        //shift all subscribers after
        //for one place to the left
        
        for(var i=index+1; i<subscriberRef.length; i++)
        {
            subscriberRef[i-1] = subscriberRef[i];
            //subscriberSelection[i-1] = subscriberSelection[i];
        }
        
        subscriberRef.length--;
    }
    
    //check if number of selected category is limited 
    //and change all subscribers accordingly
    function _onChange(object)
    {
        var selectionIndex = object.selectedIndex;
        var selection = object.options[selectionIndex].value;
        
        //find index of value of that category in category list
        var index = -1;
        for(var i=0; i<categoryValue.length; i++)
        {
            if(categoryValue[i]==selection)
            {
                index = i;
            }
        }
        
        //var totalReferences= _numberOfInstances(selection);
        var val = "";
        //if maximum number of instances for some item is reached
        //if(numberOfOccurances[index]==totalReferences)
        //{
            for(var i=0; i<subscriberRef.length; i++)
            {
                //if(subscriberRef[i].options[subscriberRef[i].selectedIndex].value != selection)
                //{
                    val = subscriberRef[i].options[subscriberRef[i].selectedIndex].value;
                    _clearOptions(subscriberRef[i]);
                    _fillOptions(subscriberRef[i]);
                    _setSelectedIndex(subscriberRef[i], val);
                //}   
            }
        //}
        
    }

    function _fillOptions(object)
    {
        var occ=0;
        var bName = navigator.appName;
        var opt = document.createElement("option");
	    opt.text = "Izaberite";
	    opt.value = -1;
	    
        if (bName == "Microsoft Internet Explorer")
        {
	        //add to category
	        object.add(opt);
	    }
	    else
	    {
	        //add to category
	        object.add(opt, null);
	    }
        for(var i in categoryValue)
        {
           occ = _numberOfInstances(categoryValue[i]);
           if(occ<numberOfOccurances[i])
           {    
                opt = document.createElement("option");
                opt.text = categoryName[i];
                opt.value = categoryValue[i];
                if (bName == "Microsoft Internet Explorer")
                {
	                //add to category
	                object.add(opt);
	            }
	            else
	            {
	                //add to category
	                object.add(opt, null);
	            }   
           }
        }
                
    }
    
    function _clearOptions(object)
    {
        var numb = object.length;
        for(var x=0; x<numb; x++)
        {
            object.remove(0);
        }
    }
    
    function _numberOfInstances(value)
    {
        var number=0;
        for(var i=0; i<subscriberRef.length; i++)
        {
            if(subscriberRef[i].options[subscriberRef[i].selectedIndex].value == value)
                number++;
        }
        return number;
    }
    
    function _setSelectedIndex(object, value)
    {
        for(var i=0; i<object.length; i++)
        {
            if(object.options[i].value == value)
                object.selectedIndex = i;
        }
    
    }
}

//encapsulates arrays with item properties
function Tables() {
	var tables = new Array();
	this.add = _add;
	this.getItem = _get;
	this.get = _get1;
	this.deleteTable = _deleteTable;
	this.getListLength = _getListLength;
	
	//get methods custom for configurator tables
	this.getName = _getName;
	this.getPrice = _getPrice;
		
	
	//adds a list reference to tables[index]
	function _add(index, list)
	{
		if(tables[index])
		{
			var tmp = tables[index];
			for(var i=0; i<tmp.length; i++)
				tmp[i] = false;
			tables[index] = false;
		}
		tables[index]=new Array();		
		var tmp = tables[index];
		for(var i=0; i<list.length; i++)
		{
			tmp[i]=list[i];
		}
	}
	
	function _get(tableIndex, itemId)
	{
		try
	    {
	        if(tables[tableIndex])
	        {
	            var table = tables[tableIndex];
	            var foundPrice = false;
	            var number = table.length;
	            var i=0;
	            var item;
    	
	            while(!foundPrice && i<number)
	            {
	                item = table[i].Item;
		            if(item.id == itemId)
		                foundPrice = true;
		            i++;
	            }
	           
	            if(foundPrice)
	               return item;
	            else    
	                return null;
	        }
	        else
	            return null;
	    }
	    catch(Error)
	    {
	        return null;
	    }
	}
	
	
	function _get1(tableIndex, listIndex)
	{
		if(tables[tableIndex])
		{
			var tmp = tables[tableIndex];
			var res= tmp[listIndex];
			return res.Item;
		}
		else
		{
			return null;
		}
	}
	
	function _deleteTable(tableIndex)
	{
	    tables[tableIndex]=null;
	    //shift all tables to one place below
	    for(var i=tableIndex+1; i<tables.length; i++)
	    {
	        tables[i-1] = tables[i];
	    }
	    tables[tables.length-1] = null;
	    tables.length = tables.length-1;
	}
	
	function _getListLength(tableIndex)
	{
	    var tmp = tables[tableIndex];
	    if(tmp)
	        return tmp.length;
	    else return 0;
	}
	
	function _getPrice(tableIndex, itemId)
	{
	    try
	    {
	        if(tables[tableIndex])
	        {
	            var table = tables[tableIndex];
	            var foundPrice = false;
	            var number = table.length;
	            var i=0;
	            var priceItem;
    	
	            while(!foundPrice && i<number)
	            {
	                priceItem = table[i].Item;
		            if(priceItem.id == itemId)
		                foundPrice = true;
		            i++;
	            }
	           
	            if(foundPrice)
	               return priceItem.cena;
	            else    
	                return 0;
	        }
	        else
	            return 0;
	    }
	    catch(Error)
	    {
	        return 0;
	    }
	
	}
	
	function _getName()
	{
	    //TODO
	}
	
}

var ModalDialogWindow;
var ModalDialogInterval;
var ModalDialog = new Object;

ModalDialog.value = '';
ModalDialog.eventhandler = '';
 

function ModalDialogMaintainFocus()
{
  try
  {
    if (ModalDialogWindow.closed)
     {
        window.clearInterval(ModalDialogInterval);
        eval(ModalDialog.eventhandler);       
        return;
     }
    ModalDialogWindow.focus(); 
  }
  catch (everything) {   }
}
        
 function ModalDialogRemoveWatch()
 {
    ModalDialog.value = '';
    ModalDialog.eventhandler = '';
 }
        
 function ModalDialogShow(Title,BodyText,Buttons,EventHandler)
 {

   ModalDialogRemoveWatch();
   ModalDialog.eventhandler = EventHandler;

   var args='width=810,height=500,left=50,top=100,toolbar=0,';
       args+='location=0,status=0,menubar=0,scrollbars=1,resizable=1';  

   ModalDialogWindow=window.open("","",args); 
   ModalDialogWindow.document.open(); 
   ModalDialogWindow.document.write('<html>');
   ModalDialogWindow.document.write('<head>'); 
   ModalDialogWindow.document.write('<meta http-equiv="Content-Type" content="text/html; charset=windows-1250" />'); 
   ModalDialogWindow.document.write('<title>' + Title + '</title>');
   ModalDialogWindow.document.write('<link href="stil/cenovnik.css" rel="stylesheet" type="text/css" />');
   ModalDialogWindow.document.write('<link href="style/screen.css" rel="stylesheet" type="text/css" />');
   ModalDialogWindow.document.write('<script' + ' language=JavaScript>');
   ModalDialogWindow.document.write('function CloseForm(Response) ');
   ModalDialogWindow.document.write('{ ');
   ModalDialogWindow.document.write(' window.opener.ModalDialog.value = Response; ');
   ModalDialogWindow.document.write(' window.close(); ');
   ModalDialogWindow.document.write('} ');
   ModalDialogWindow.document.write('function Print() ');
   ModalDialogWindow.document.write('{ ');
   ModalDialogWindow.document.write(' window.print(); ');
   ModalDialogWindow.document.write('} ');
   ModalDialogWindow.document.write('</script' + '>');        
   ModalDialogWindow.document.write('</head>');   
   ModalDialogWindow.document.write('<body>');
   ModalDialogWindow.document.write('<table class="tblCont" border=0 width="770" align=center cellspacing=0 cellpadding=2 style="margin:0 20px;">');
   ModalDialogWindow.document.write('<tr><td align=left>' + BodyText + '</td></tr>');
   ModalDialogWindow.document.write('<tr><td>' + Buttons + '</td></tr>');
   ModalDialogWindow.document.write('</body>');
   ModalDialogWindow.document.write('</html>'); 
   ModalDialogWindow.document.close(); 
   ModalDialogWindow.focus(); 
   ModalDialogInterval = window.setInterval("ModalDialogMaintainFocus()",5);

 }
 
 function ConfirmConfiguration(BodyText,EventHandler)
{
    var Buttons=''; 
    Buttons = '<div class="popup-naruci"><a href=javascript:CloseForm("Naruci");>Naruči</a></div>';
    Buttons += '<div class="popup-otkazi"><a href=javascript:CloseForm("Otkazi");>Otkaži</a></div>';
    Buttons += '<div class="popup-print"><a href=javascript:window.print();>Štampaj</a></div>';
    ModalDialogShow("Potvrda narudžbine konfiguracije",BodyText,Buttons,EventHandler);
    //return true;
}

function ConfirmConfigurationReturnMethod()
{
    var retval = ModalDialog.value;
    
    if(retval == "Naruci")
    {
        SubmitConfiguration();
        return true;
    }
    else if(retval == "Stampaj")
    {
        //print(ModalDialog.document);
        //window.print();
        ModalDialogWindow.print();
        //return false;
    }
    else
        return false;
}

