/* IE6 flicker fix
-------------------------------------------------- */
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}
    
    var Flash;
    var uploadedfilescount = 0;
    var uploadUrl = "uploadfiles.aspx";
    
    window.onload = function() {    
        InitFlashObj();
    }
    
    //Init "flash" object
    function InitFlashObj()
    {
        if(document.embeds && document.embeds.length>=1 && navigator.userAgent.indexOf("Safari") == -1)
            Flash = document.getElementById("EmbedFlashFilesUpload");
            
        else
            Flash = document.getElementById("FlashFilesUpload");
    }
    
    /*
        MultiPowUpload_onMovieLoad. Invoked when the movie loaded and if browsers supports ExternalInterface i.e 
         programming interface that enables straightforward communication between Flash Movie and JavaScript.
    */
    function MultiPowUpload_onMovieLoad()
    {
        InitFlashObj(); //sometimes Flash not initialized while window.onload event
        Flash.width = 1;
        Flash.height = 1;
        
        var JSUpload = document.getElementById("JSUpload");
        JSUpload.style.visibility = "visible";
        JSUpload.style.width = 350;
        JSUpload.style.height = 300;    
    }
    
    /*
        flash.browseFiles(typelist) displays a file-browsing dialog box in which the user can select a local file to upload. 
        The dialog box is native to the user's operating system.
        typelist - An array of file types used to filter the files displayed in the dialog box.
    */
    function browsefiles()
    {
        var allTypes = new Array();
        var imageTypes = new Object();
        imageTypes.description = "All files";
        imageTypes.extension = "*.*";
        allTypes.push(imageTypes);    
        imageTypes = new Object();
        imageTypes.description = "Images (*.JPG;*.JPEG;*.JPE;*.GIF;*.PNG;)";
        imageTypes.extension = "*.jpg; *.jpeg; *.jpe; *.gif; *.png;";
        allTypes.push(imageTypes);    
        Flash.browseFiles(allTypes);
    }
    
    //Clear list
    function clearListBox(lstBox)
    {        
        while (lstBox.length > 0)
        {
            lstBox.remove(0);
        }
    }
    
    //Update HTML progress bar state
    function updateProgressBar(percentDone)
    {
        var rowProgress = document.getElementById("rowProgress");
        if(percentDone>=1)
            rowProgress.width = percentDone + "%";
        else
            rowProgress.width = "1";
    }
    
    /*
        flash.uploadAll(url) Starts the upload of a files in list to a remote server.
        url - The URL of the server script configured to handle upload through HTTP POST calls.
    */
    function upload()
    {
        updateProgressBar(0);
        uploadedfilescount = 0;
        document.getElementById("lable").innerHTML = "";
        Flash.uploadAll(uploadUrl);
    }
    
    //MultiPowUpload_onSelect. Invoked when the user selects a file to upload or download from the file-browsing dialog box.
    function MultiPowUpload_onSelect()
    {
        var list = Flash.fileList();
        var fileslist = document.getElementById("fileslist");
        var i = 0;
        clearListBox(fileslist);
        for(i=0; i<list.length; i++)
        {
            fileslist.options[fileslist.options.length] = new Option(list[i].name + 
            " (" + list[i].size + " bytes)", i, false, false );
        }
    }
    
    //MultiPowUpload_onProgress. Invoked periodically during the file upload or download operation
    function MultiPowUpload_onProgress(type, index, fileBytesLoaded, fileBytesLength, totalBytesLoaded, totalBytesLength) 
    {
       var PercentDone = new Number((totalBytesLoaded/totalBytesLength)*100).toFixed(1);
       document.getElementById("lable").innerHTML = PercentDone + "% uploaded" + " (" + uploadedfilescount + " files)";
       updateProgressBar(PercentDone);
    }
    
    //MultiPowUpload_onError. Invoked when an input/output error occurs or when an upload/download fails because of an HTTP error
    function MultiPowUpload_onError(type, index, error) 
    {
       window.alert(error);
    }
    
    //MultiPowUpload_onComplete. Invoked when the upload or download of single file operation has successfully completed
    function MultiPowUpload_onComplete(type, index)
    {
        uploadedfilescount++;
    }
    
    //MultiPowUpload_onCompleteAbsolute. Invoked when the upload or download of all files operation has successfully completed
    function MultiPowUpload_onCompleteAbsolute(type, totalBytesLoaded)
    {
      document.getElementById("lable").innerHTML = "Upload complete! Total bytes " + totalBytesLoaded + " (" + uploadedfilescount + " files)";
        var fileslist = document.getElementById("fileslist");
        clearListBox(fileslist);
    }
    
	function calculateOrderSum() {
		
		orderSum = 0;
		var photoCount = 0;
		var whiteFrames = document.getElementById('whiteFrames');	

		var whiteMarginPrintoutPrice = parseFloat(whiteMarginPrintoutPriceTemp);
		var deliveryToPostOfficePrice = parseFloat(deliveryToPostOfficeTemp);

		for(var i = 0; i < photoIdArray.length; i++) {
			var photoId = photoIdArray[i];
			var elementId = 'photo_dimensions_' + photoId.id;
			var photoPrice = document.getElementById(elementId);
			var selectedIndex = photoPrice.selectedIndex;
			
			var selectList = document.getElementById(elementId);
			var options = selectList.options;
			
			var amountOptions = document.getElementById('photo_amount_' + photoId.id).options;
			
			for(var j = 0; j < options.length; j++) {
				var option = options[j];
				if(option.selected == true) {
					for(var h = 0; h < productArray.length; h++) {
						var product = productArray[h];
						if(product.id == option.value) {
							var selectedAmountIndex = document.getElementById('photo_amount_' + photoId.id).selectedIndex;
							
							if(whiteFrames.checked) {							
								orderSum += (parseFloat(product.price) + whiteMarginPrintoutPrice) * (parseInt(selectedAmountIndex) + 1);
							} else {
								orderSum += parseFloat(product.price) * (parseInt(selectedAmountIndex) + 1);
							}
							photoCount += parseInt(selectedAmountIndex) + 1;
						}
					}
				}
			}
					
		}

		if(deliveryToPostOfficeCode == document.getElementById('deliveryMode').value) {
			orderSum += deliveryToPostOfficePrice;
		}
		
		document.getElementById('orderSum').innerHTML = orderSum + ' <s:message code="crown"/>';
		
		if(photoCount == 1) {
			document.getElementById('photoCount').innerHTML = photoCount + ' ' + pictureStrSingle;			
		} else {
			document.getElementById('photoCount').innerHTML = photoCount + ' ' + pictureStrPlural;
		}
		
	};

	function submitForm(formElementId) {
		document.getElementById(formElementId).submit();
	}
	
	function submitFormAsConfirm() {
		var photoForm = document.getElementById(photoFormId);
		photoForm.action = confirmUrl;
		photoForm.submit();
	}
	
	function deliveryModeChanged() {

		var dmcrow = document.getElementById("deliveryModes");		
		
		var row = document.getElementById("deliveryModes");
		var sbox = document.getElementById("deliveryMode");
		
		var tbox = document.getElementById("town");
		var stbox = document.getElementById("street");
		var hbox = document.getElementById("house");
		var apbox = document.getElementById("apartment");
		var zbox = document.getElementById("zip");								
		
		var selDeliveryMode = sbox.options[sbox.selectedIndex].value;
		if(selDeliveryMode == deliveryToShopCode) {

			dmcrow.style.display = '';
			
			row.style.display = 'none';

			tbox.style.display='';
			stbox.style.display='';
			hbox.style.display='';
			apbox.style.display='';
			zbox.style.display='';
		} else {

			dmcrow.style.display = 'none';
			row.style.display = '';
			
			tbox.style.display='none';
			stbox.style.display='none';
			hbox.style.display='none';
			apbox.style.display='none';
			zbox.style.display='none';
		}
	}
	
	function submitReadAgreement() {
		
		var agreementSubmitHiddenValue = document.getElementById('readAgreementSubmit');
		agreementSubmitHiddenValue.value = 'true';
		
		var photoForm = document.getElementById(photoFormId);
		photoForm.action = defaultUrl;
		photoForm.submit();
	}
	
	function submitFileDelete(fileId) {

		var linkEl = document.getElementById('fileDeleteLink_' + fileId);

		if(linkEl != null) {
			
			var href = linkEl.getAttribute("href");
			
	   		if(href != null && href != "" && href){
	      		linkEl.setAttribute('href', 'javascript: void(0);');
	   		}
		}

		var photoForm = document.getElementById(photoFormId);
		photoForm.action = defaultUrl + '?fileDeleteRequest=1' + '&photoId=' + fileId;
		
		photoForm.submit();
	}
	
    /**
     * Function : dump()
     * Arguments: The data - array,hash(associative array),object
     *    The level - OPTIONAL
     * Returns  : The textual representation of the array.
     * This function was inspired by the print_r function of PHP.
     * This will accept some data as the argument and return a
     * text that will be a more readable version of the
     * array/hash/object that is given.
     * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
     */
    function dump(arr,level) {
    	var dumped_text = "";
    	if(!level) level = 0;
    	
    	if(level > 0) // no recursion
    		return;
    	
    	//The padding given at the beginning of the line.
    	var level_padding = "";
    	for(var j=0;j<level+1;j++) level_padding += "    ";
    	
    	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    		for(var item in arr) {
    			var value = arr[item];
    			
    			if(typeof(value) == 'object') { //If it is an array,
    				dumped_text += level_padding + "'" + item + "' ...\n";
    				dumped_text += dump(value,level+1);
    			} else {
    				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
    			}
    		}
    	} else { //Stings/Chars/Numbers etc.
    		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    	}
    	return dumped_text;
    }