//check if browser is IE
var IE = document.all?true:false
var web_root;
var folder = '/framework/images/gallery/details/';
var folder_thumbs = '/framework/images/gallery/thumbnails/';
var errors = new Array();
errors['required'] = new Array();
errors['required']['ro'] = 'Camp obligatoriu';
errors['required']['en'] = 'Required field';
errors['invalid_email'] = new Array();
errors['invalid_email']['ro'] = 'Adresa de e-mail invalida';
errors['invalid_email']['en'] = 'Invalid e-mail address';

var messages = new Array();
messages['sending_mail'] = new Array();
messages['sending_mail']['ro'] = 'Se trimite mesajul';
messages['sending_mail']['en'] = 'Sending e-mail';

messages['changing_language'] = new Array();
messages['changing_language']['ro'] = 'Se schimba limba';
messages['changing_language']['en'] = 'Changing language';

messages['loading'] = new Array();
messages['loading']['ro'] = 'se incarca...';
messages['loading']['en'] = 'loading...';

messages['subcategories'] = new Array();
messages['subcategories']['ro'] = 'se incarca continutul categoriei...';
messages['subcategories']['en'] = 'loading category content...';

messages['select_category'] = new Array();
messages['select_category']['ro'] = 'Selectati o categorie';
messages['select_category']['en'] = 'Select a category';

messages['select_subcategory'] = new Array();
messages['select_subcategory']['ro'] = 'Selectati o subcategorie';
messages['select_subcategory']['en'] = 'Select a subcategory';

messages['no_subcategory'] = new Array();
messages['no_subcategory']['ro'] = 'Nu exista subcategorii in categoria selectata';
messages['no_subcategory']['en'] = 'There are no subcategories in the selected category';

messages['thumbnails'] = new Array();
messages['thumbnails']['ro'] = 'se incarca continutul subcategoriei...';
messages['thumbnails']['en'] = 'loading subcategory content...';

messages['no_images'] = new Array();
messages['no_images']['ro'] = 'Nu exista imagini in subcategoria selectata';
messages['no_images']['en'] = 'There are no images in the selected subcategory';

messages['image'] = new Array();
messages['image']['ro'] = 'se incarca imaginea...';
messages['image']['en'] = 'loading image...';

messages['det_image'] = new Array();
messages['det_image']['ro'] = 'Selectati o imagine';
messages['det_image']['en'] = 'Select an image';

messages['no_det_image'] = new Array();
messages['no_det_image']['ro'] = 'Eroare la afisarea imaginii';
messages['no_det_image']['en'] = 'Error displaying image';

messages['no_description'] = new Array();
messages['no_description']['ro'] = 'Nu exista descriere';
messages['no_description']['en'] = 'No description available';

messages['page'] = new Array();
messages['page']['ro'] = 'Pagina';
messages['page']['en'] = 'Page';

function prepareRequest(buttonObj, language, func){
  	
	//get the additional params to be posted 
  	var params = getFormValues(buttonObj);
  	if (func == 'contact'){
      	if (validateContactForm()){
        	sendAjaxRequest(params, func);
        }
    } else {
        if (validateWebContactForm()){
        	sendAjaxRequest(params, func);
        }
    }
}

//this function sends the ajax request
function sendAjaxRequest(params, func){
    document.getElementById("loader").innerHTML = messages['sending_mail'][GLOBAL_language];
    document.getElementById("loader").style.visibility='visible';
	$.ajax(
		{ 
			type: "POST",
			url: "/contact/0/0/0/1/"+func+"/ajax",
			data: 'helper=true'+params,
			dataType: "html",
			complete: function(xml) {
				document.getElementById("loader").style.visibility='hidden';
			},
			success: function(xml){
                if (func == 'contact'){
                    document.getElementById('message_field').innerHTML = xml;
                } else {
                    document.getElementById('message_field2').innerHTML = xml;
                }
			},
			error: function(xml) {
                document.getElementById("loader").style.visibility='hidden';
				alert('Error comunicating with the server (sar)!');
			}
		}
	);	
}



function getFormValues(buttonObj){
    formObject = buttonObj.parentNode;
    while (formObject.nodeName != 'FORM'){
        formObject = formObject.parentNode;
    }
	var elementsArray = formObject.elements;
	var nrOfFields = elementsArray.length;
	var qry = '';
	for(i=0; i<nrOfFields;i++){
	  	if (elementsArray[i].id){	
			qry += '&'+elementsArray[i].id+'='+elementsArray[i].value
		} else if (elementsArray[i].name) {
		  	qry += '&'+elementsArray[i].name+'='+elementsArray[i].value
		}
	}
	return qry;
}

function clearErrors(){
    document.getElementById('error_nume').innerHTML = '';
    document.getElementById('error_prenume').innerHTML = '';
    document.getElementById('error_email').innerHTML = '';
    document.getElementById('error_mesaj').innerHTML = '';
    document.getElementById('message_field').innerHTML = '';
}

function clearWebErrors(){
    document.getElementById('error_nume2').innerHTML = '';
    document.getElementById('error_prenume2').innerHTML = '';
    document.getElementById('error_email2').innerHTML = '';
    document.getElementById('error_mesaj2').innerHTML = '';
    document.getElementById('message_field2').innerHTML = '';
}

function validateContactForm(){
    clearErrors();
    var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;
    var ok = true;
    var nume = document.getElementById('nume').value;
    if (nume == ''){
        ok = false;
        document.getElementById('error_nume').innerHTML = errors['required'][GLOBAL_language];
    }
    var prenume = document.getElementById('prenume').value;
    if (prenume == ''){
        ok = false;
        document.getElementById('error_prenume').innerHTML = errors['required'][GLOBAL_language];
    }
    var email = document.getElementById('email').value;
    var emailTest =  objRE.test(email);
    if (email == ''){
        ok = false;
        document.getElementById('error_email').innerHTML = errors['required'][GLOBAL_language];
    } else if (!emailTest){
        ok = false;
        document.getElementById('error_email').innerHTML = errors['invalid_email'][GLOBAL_language];
    }
    var mesaj = document.getElementById('mesaj').value;
    if (mesaj == ''){
        ok = false;
        document.getElementById('error_mesaj').innerHTML = errors['required'][GLOBAL_language];
    }
    return ok;
}

function validateWebContactForm(){
    clearWebErrors();
    var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;
    var ok = true;
    var nume = document.getElementById('nume2').value;
    if (nume == ''){
        ok = false;
        document.getElementById('error_nume2').innerHTML = errors['required'][GLOBAL_language];
    }
    var prenume = document.getElementById('prenume2').value;
    if (prenume == ''){
        ok = false;
        document.getElementById('error_prenume2').innerHTML = errors['required'][GLOBAL_language];
    }
    var email = document.getElementById('email2').value;
    var emailTest =  objRE.test(email);
    if (email == ''){
        ok = false;
        document.getElementById('error_email2').innerHTML = errors['required'][GLOBAL_language];
    } else if (!emailTest){
        ok = false;
        document.getElementById('error_email2').innerHTML = errors['invalid_email'][GLOBAL_language];
    }
    var mesaj = document.getElementById('mesaj2').value;
    if (mesaj == ''){
        ok = false;
        document.getElementById('error_mesaj2').innerHTML = errors['required'][GLOBAL_language];
    }
    return ok;
}


function changeCategory(module, cat){
    GLOBAL_category = cat;
    if (GLOBAL_internal_cat_action != 'language'){
        GLOBAL_subcategory = 0;
    }
    clearPages();
    document.getElementById("loader").innerHTML = messages['subcategories'][GLOBAL_language];
    document.getElementById("loader").style.visibility='visible';
    if (cat != '0'){
    	$.ajax(
    		{
    			type: "GET",
    			url: "/gallery/"+GLOBAL_category+"/0/0/1/aqxrw/ajax",
    			data: '',
    			dataType: "xml",
    			complete: function(xml) {
    				
    			},
    			success: function(xml){
    				optionsList = $('option', xml);
    				//subcategory select box
    				var sel = document.getElementById('subcat_sel');
    				//remove options
                    var len = sel.options.length;
                    for(i=0; i<len; i++){
                        sel.removeChild(sel.options[0]);
                    }
                    //clear thumbs
                        ths = document.getElementById("thumbs_list").getElementsByTagName('DIV');
                        var len = ths.length;
                        for(i=len-1; i>=0; i--){
                            if (ths[i].id.substring(0, 10) == 'tmp_div_id'){
                                document.getElementById("thumbs_list").removeChild(document.getElementById(ths[i].id));
                            }
                        }
                    //if there are subcategories
    				if (optionsList.size() > 0) {
                        //create an empty option
                        var option = document.createElement("option");
                        //create an empty value to it
                        option.setAttribute("value", 0);
                        //create an empty text for it
                        newText = document.createTextNode("");
                        //assign the empty text to the option
                        option.appendChild(newText);
                        //add the option to the subcategories drop down box
                        sel.appendChild(option);
                        //count subcategories
                        var nr_of_subcategories = 0;
                        //for each found subcategories
    					optionsList.each(
    						function (){
                                //if the xml field refers to the subcategory
                                if (this.getAttribute("type") != 'category'){
                                    //create a new option
                                    var option = document.createElement("option");
                                    //assign a value
          	                        option.setAttribute("value", this.getAttribute("id"));
          	                        //create a text
          	                        newText = document.createTextNode($(this).text());
          	                        //assign the text
          	                        option.appendChild(newText);
          	                        //add the option
          	                        sel.appendChild(option);
          	                        //increase subcategories
          	                        nr_of_subcategories++;
                                //if the xml field refers to the category
      	                        } else {
                                    //the div that contains the images
                                    var div = document.getElementById('img_container');
                                    //the it's' dimensions
                                    var w = div.offsetWidth-5;
                                    var h = div.offsetHeight-5;
                                    //if there is an image
                                    if (this.getAttribute("img") != ''){
                                        //the message div
                                        var msg_div = document.getElementById('no_image');
                                        //if it exists
                                        if (msg_div){
                                            //remove it
                                            div.removeChild(msg_div);
                                        }
                                        //the detail image
                                        var img_div = document.getElementById('detail_img');
                                        //if it exists
                                        if (img_div){
                                            //get image width and height
                                            var iw = this.getAttribute("width");
                                            var ih = this.getAttribute("height");
                                            //calculate ration
                                            var dimensions = calculateRatio(iw, ih, w, h);
                                            //display new image
                                            displayDetailImage(this.getAttribute("img"), dimensions['width'], dimensions['height']);
                                        //if it does not exists
                                        } else {
                                            //the message div
                                            var msg_div = document.getElementById('no_image');
                                            //if it exists
                                            if (msg_div){
                                                //remove it
                                                div.removeChild(msg_div);
                                            }
                                            //get image width and height
                                            var iw = this.getAttribute("width");
                                            var ih = this.getAttribute("height");
                                            //calculate ration
                                            var dimensions = calculateRatio(iw, ih, w, h);
                                            //display new image
                                            displayDetailImage(this.getAttribute("img"), dimensions['width'], dimensions['height']);
                                        }
                                    //if there is no image
                                    } else {
                                        displayDetailMessage();
                                    }
                                    //if there is title
                                    if (this.getAttribute("title") != ''){
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //clean the div
                                            txt_div.innerHTML = '';
                                            //create a new paragraph
                                            var par = document.createElement("p");
                                            //assign a class
                                            par.setAttribute("id", "p_b");
                                            //create a new text
                                            newText = document.createTextNode(this.getAttribute("title"));
                                            //assign the text to the paragraph
                                            par.appendChild(newText);
                                            //assign the paragraph to the div
                                            txt_div.appendChild(par);
                                            //assign a class
                                            document.getElementById('p_b').className = 'p_b';
                                        }
                                    } else {
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //write empty text to it
                                            txt_div.innerHTML = '';
                                        }
                                    }
                                    //if there is description
                                    if ($(this).text() != ''){
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //the message div
                                            var msg_div = document.getElementById('no_description');
                                            //if it exists
                                            if (msg_div){
                                                //remove it
                                                txt_div.removeChild(msg_div);
                                            }
                                            //create a new paragraph
                                            var par = document.createElement("p");
                                            //create a new text
                                            newText = document.createTextNode($(this).text());
                                            //assign the text to the paragraph
                                            par.appendChild(newText);
                                            //assign the paragraph to the div
                                            txt_div.appendChild(par);
                                        }
                                    //if there is no description
                                    } else {
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //if there is no title
                                            if (!this.getAttribute("title")){
                                                clearText();
                                            }
                                        }
                                    }
                                }
    						}
    					);
                    //if there are no subcategories
                    if (nr_of_subcategories == 0){
                        //display no subcategory message
                        displayLeftMessage('no_subcategory');
                    //if there are subcategories
                    } else {
                        //display select subcategory message
                        displayLeftMessage('select_subcategory');
                    }
                    //if there are no subcategories
    				} else {
    					document.getElementById('no_thumbs').innerHTML = messages['no_subcategory'][GLOBAL_language];
    				}
    				document.getElementById("loader").style.visibility='hidden';
    				if (GLOBAL_internal_cat_action == 'language'){
                        GLOBAL_internal_cat_action = '';
                        GLOBAL_internal_subcat_action = 'language';
                        changeGallerySubcategory();
                    }
    			},
    			error: function(xml) {
                    document.getElementById("loader").style.visibility='hidden';
    				alert('Error comunicating with the server (cats)!');
    			}
    		}
    	);
    } else {
        //reset subcategory select box
		var sel = document.getElementById('subcat_sel');
		//remove options
        var len = sel.options.length;
        for(i=0; i<len; i++){
            sel.removeChild(sel.options[0]);
        }
        //clear thumbs
        ths = document.getElementById("thumbs_list").getElementsByTagName('DIV');
        var len = ths.length;
        for(i=len-1; i>=0; i--){
            if (ths[i].id.substring(0, 10) == 'tmp_div_id'){
                document.getElementById("thumbs_list").removeChild(document.getElementById(ths[i].id));
            }
        }
        displayDetailMessage();
        clearText();
        //display select category message
        displayLeftMessage('select_category');
        //hide loader
        document.getElementById("loader").style.visibility='hidden';
    }
}

function changeSubcategory(module, subcat, page){
    if (!page){
        page = 1;
    }
    GLOBAL_subcategory = subcat;
    if (GLOBAL_internal_subcat_action != 'language'){
        GLOBAL_item = 0;
    }
    GLOBAL_page = page;
    document.getElementById("loader").innerHTML = messages['thumbnails'][GLOBAL_language];
    document.getElementById("loader").style.visibility='visible';
    if (subcat != '0'){
    	$.ajax(
    		{
    			type: "GET",
    			url: "/gallery/"+GLOBAL_category+"/"+GLOBAL_subcategory+"/0/"+GLOBAL_page+"/aqxrw/ajax",
    			data: '',
    			dataType: "xml",
    			complete: function(xml) {
    				
    			},
    			success: function(xml){// alert(xml);
    				optionsList = $('option', xml);
    				//if there are images
    				if (optionsList.size() > 0) {
                        //clear message
                        paren = document.getElementById('thumbs_list');
                        chil = document.getElementById('no_thumbs');
                        if (chil){
                            paren.removeChild(chil);
                        }
                        //clear thumbs
                        ths = document.getElementById("thumbs_list").getElementsByTagName('DIV');
                        var len = ths.length;
                        for(i=len-1; i>=0; i--){
                            if (ths[i].id.substring(0, 10) == 'tmp_div_id'){
                                document.getElementById("thumbs_list").removeChild(document.getElementById(ths[i].id));
                            }
                        }
                        //set a counter
                        var counter=0;
                        //for each found subcategories
    					optionsList.each(
                            function(){
                                //if the xml field refers to the images
                                if (this.getAttribute("type") != 'subcategory'){
                                    //create a new div
                                    var thumb_div = document.createElement("div");
                                    //assign an id
                                    thumb_div.setAttribute("id", "tmp_div_id_"+counter);
                                    //add div
                                    document.getElementById("thumbs_list").appendChild(thumb_div);
                                    //assign a class
                                    document.getElementById("tmp_div_id_"+counter).className = 'thumb';
                                    
                                    //the div that contains the images
                                    var t_div = document.getElementById("tmp_div_id_"+counter);
                                    //the it's' dimensions
                                    var tw = t_div.offsetWidth-5;
                                    var th = t_div.offsetHeight-5;
                                    
                                    if (this.getAttribute("img") != ''){

                                        //create the loading div for thumbnail
                                         var img_loading_div = document.createElement("div");
                                         img_loading_div.setAttribute("id", "thumb_loadig_div"+counter);
                                         thumbLoadingText = document.createTextNode(messages['loading'][GLOBAL_language]);
                                         //assign the text to the div
                                         img_loading_div.appendChild(thumbLoadingText);
                                         //add the loading div
                                         thumb_div.appendChild(img_loading_div);
                                         //assign a class
                                         document.getElementById("thumb_loadig_div"+counter).className = 'thumb_loading_div';
                                        //get image width and height
                                        var tiw = this.getAttribute("width");
                                        var tih = this.getAttribute("height");
                                        dims = calculateRatio(tiw, tih, tw, th);
                                        //display image
                                        displayThumbnailImage("tmp_div_id_"+counter, "tmp_img_id_"+counter, folder_thumbs+this.getAttribute("img"), dims['width'], dims['height'], this.getAttribute("id"));
                                        //add event to remove loader on image load
                                        timg = document.getElementById("tmp_img_id_"+counter);
                                        timg.onload = function(){
                                            var count = this.id.substring(11);
                                            cont = document.getElementById("tmp_div_id_"+count);
                                            lodr = document.getElementById("thumb_loadig_div"+count);
                                            lodr.style.visibility = 'hidden';
                                            cont.removeChild(lodr);
                                        };
                                        //remove loading div margin for IE
                                        if (IE){
                                            margin = document.getElementById("tmp_div_id_"+counter).offsetLeft;
                                            margin = parseInt(margin)+3;
                                            document.getElementById("thumb_loadig_div"+counter).style.left = margin+'px';
                                        }
                                    }
                                    //increase counter
                                    counter++;
                                //if the xml field refers to the subcategory
      	                        } else {
                                    //handle pagination
                                    var total_pages = this.getAttribute("total_pages");
                                    var label_cell = document.getElementById('pages_label');
                                    var pages_cell = document.getElementById('pages_values');
                                    //if there is more than one page
                                    if (total_pages > 1){
                                        clearPages();
                                        createPages(total_pages);
                                    //if there are no pages clear current pages
                                    } else {
                                        clearPages();
                                    }
                                    //the div that contains the images
                                    var div = document.getElementById('img_container');
                                    //the it's' dimensions
                                    var w = div.offsetWidth-5;
                                    var h = div.offsetHeight-5;
                                    //if there is an image
                                    if (this.getAttribute("img") != ''){
                                        //the message div
                                        var msg_div = document.getElementById('no_image');
                                        //if it exists
                                        if (msg_div){
                                            //remove it
                                            div.removeChild(msg_div);
                                        }
                                        //the detail image
                                        var img_div = document.getElementById('detail_img');
                                        //if it exists
                                        if (img_div){
                                            //get image width and height
                                            var iw = this.getAttribute("width");
                                            var ih = this.getAttribute("height");
                                            //calculate ration
                                            var dimensions = calculateRatio(iw, ih, w, h);
                                            displayDetailImage(this.getAttribute("img"), dimensions['width'], dimensions['height']);
                                        //if it does not exists
                                        } else {
                                            //the message div
                                            var msg_div = document.getElementById('no_image');
                                            //if it exists
                                            if (msg_div){
                                                //remove it
                                                div.removeChild(msg_div);
                                            }
                                            //get image width and height
                                            var iw = this.getAttribute("width");
                                            var ih = this.getAttribute("height");
                                            //calculate ration
                                            var dimensions = calculateRatio(iw, ih, w, h);
                                            //display new image
                                            displayDetailImage(this.getAttribute("img"), dimensions['width'], dimensions['height']);
                                        }
                                    //if there is no image
                                    } else {
                                        //the message div
                                        var msg_div = document.getElementById('no_image');
                                        //if it does not exists
                                        if (!msg_div){
                                            //the detail image
                                            var img_div = document.getElementById('detail_img');
                                            //if it exists
                                            if (img_div){
                                                //remove it
                                                div.removeChild(img_div);
                                            }
                                            //create a new div
                                            var text_div = document.createElement("div");
                                            //assign an id
                                            text_div.setAttribute("id", "no_image");
                                            //create a new text
                                            newText = document.createTextNode(messages['det_image'][GLOBAL_language]);
                                            //assign the text to the div
                                            text_div.appendChild(newText);
                                            //add the div
                                            div.appendChild(text_div);
                                        //if it exists
                                        } else {
                                            //the detail image
                                            var img_div = document.getElementById('detail_img');
                                            //if it exists
                                            if (img_div){
                                                //remove it
                                                div.removeChild(img_div);
                                            }
                                            //write the message
                                            msg_div.innerHtml = messages['det_image'][GLOBAL_language];
                                        }
                                    }
                                    //if there is title
                                    if (this.getAttribute("title") != ''){
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //clean the div
                                            txt_div.innerHTML = '';
                                            //create a new paragraph
                                            var par = document.createElement("p");
                                            //assign a class
                                            par.setAttribute("id", "p_b");
                                            //create a new text
                                            newText = document.createTextNode(this.getAttribute("title"));
                                            //assign the text to the paragraph
                                            par.appendChild(newText);
                                            //assign the paragraph to the div
                                            txt_div.appendChild(par);
                                            //assign a class
                                            document.getElementById('p_b').className = 'p_b';
                                        }
                                    } else {
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //write empty text to it
                                            txt_div.innerHTML = '';
                                        }
                                    }
                                    //if there is description
                                    if ($(this).text() != ''){
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //the message div
                                            var msg_div = document.getElementById('no_description');
                                            //if it exists
                                            if (msg_div){
                                                //remove it
                                                txt_div.removeChild(msg_div);
                                            }
                                            //create a new paragraph
                                            var par = document.createElement("p");
                                            //create a new text
                                            newText = document.createTextNode($(this).text());
                                            //assign the text to the paragraph
                                            par.appendChild(newText);
                                            //assign the paragraph to the div
                                            txt_div.appendChild(par);
                                        }
                                    //if there is no description
                                    } else {
                                        //the text div
                                        var txt_div = document.getElementById('detail_text');
                                        //if it exists
                                        if (txt_div){
                                            //if there is no title
                                            if (!this.getAttribute("title")){
                                                clearText();
                                            }
                                        }
                                    }
                                }
                            }
                        );
                    //if there are no images
                    if (counter == 0){
                        //display no images message
                        displayLeftMessage('no_images');
                    }
                    //if there are no images
    				} else {
                        //display no images message
                        displayLeftMessage('no_images');
        		    }
        		    document.getElementById("loader").style.visibility='hidden';
        		    if (GLOBAL_internal_subcat_action == 'language'){
                        GLOBAL_internal_subcat_action = '';
                        GLOBAL_internal_item_action = 'language';
                        changeGalleryImage();
                    }
    			},
    			error: function(xml) {
                    document.getElementById("loader").style.visibility='hidden';
    				alert('Error comunicating with the server (subs)!');
    			}
    		}
    	);
    } else {
        changeCategory(module, GLOBAL_category);
    }
}

function createTextPage(pageText){
    var pages_cell = document.getElementById('pages_values');
    //create a new text
    newText = document.createTextNode(' '+pageText+' ');
    //add the link
    pages_cell.appendChild(newText);
}

function createLinkPage(pageText){
    var pages_cell = document.getElementById('pages_values');
    //create a page link
    var pageLink = document.createElement('a');
    //define the href
    pageLink.setAttribute("href", "#");
    //define the id
    pageLink.setAttribute("id", pageText);
    if (pageText != '...'){
        //set the onclick event
        pageLink.onclick = function(){
            changeSubcategory('gallery', GLOBAL_subcategory, this.id);
        }
    }
    //create a new text
    newText = document.createTextNode(' '+pageText+' ');
    //assign the text to the link
    pageLink.appendChild(newText);
    //add the link
    pages_cell.appendChild(pageLink);
}

function createPages(total_pages){
    var label_cell = document.getElementById('pages_label');
    var pages_cell = document.getElementById('pages_values');
    //display the label
    label_cell.innerHTML = messages['page'][GLOBAL_language];
    var delta_left = false;
    var delta_right = false;
    var show_pages = 8;
    if (total_pages <= show_pages){
        var limit_start = 1;
        var limit_stop = total_pages;
    } else {
        GLOBAL_page = parseInt(GLOBAL_page);
        var pages_left = Math.ceil((show_pages/2)-1);
        var pages_right = parseInt(show_pages - pages_left - 1);
        var limit_start = GLOBAL_page - pages_left;
        var limit_stop = GLOBAL_page + pages_right;
        if (limit_start < 1){
            dif = 1 - limit_start;
            limit_start = 1;
            limit_stop += dif;
        } else if (limit_stop > total_pages) {
            dif = limit_stop - total_pages;
            limit_stop = total_pages;
            limit_start -= dif;
        }
    }
    if (GLOBAL_page > 1){
        createImageLink('laquo.jpg', 'prev', delta_left);
    }
    if (limit_start > 1){
        createLinkPage('...');
    }
    for (i=limit_start; i<=limit_stop; i++){
        //define page
        var page = i;
        //if the page is the current page
        if(page == GLOBAL_page){
            createTextPage(page);
        } else {
            createLinkPage(page);
        }
    }
    if (limit_stop < total_pages){
        createLinkPage('...');
    }
    if (GLOBAL_page < total_pages){
        createImageLink('raquo.jpg', 'next', delta_right);
    }
}

function createImageLink(img, direction){
    var pages_cell = document.getElementById('pages_values');
    //create a page link
    var imageLink = document.createElement('img');
    //define the src
    imageLink.setAttribute("src", "/framework/images/graphics/"+img);
    //create a page link
    var pageLink = document.createElement('a');
    //define the href
    pageLink.setAttribute("href", "#");
    //assign the image to the link
    pageLink.appendChild(imageLink);
    //set the onclick event
    pageLink.onclick = function(){
        if (direction == 'next'){
            changeSubcategory('gallery', GLOBAL_subcategory, parseInt(GLOBAL_page+1));
        } else {
            changeSubcategory('gallery', GLOBAL_subcategory, parseInt(GLOBAL_page-1));
        }
    }
    //add the link
    pages_cell.appendChild(pageLink);
}

function clearPages(){
    var label_cell = document.getElementById('pages_label');
    var pages_cell = document.getElementById('pages_values');
    var a = pages_cell.getElementsByTagName('A');
    while (pages_cell.firstChild){
        pages_cell.removeChild(pages_cell.firstChild);
    }
    label_cell.innerHTML = '';
}

function changeImage(db_id){
    var cat = GLOBAL_category;
    var subcat = GLOBAL_subcategory;
    GLOBAL_item = db_id;
    $.ajax(
    		{
    			type: "GET",
    			url: "/gallery/"+cat+"/"+subcat+"/"+db_id+"/1/aqxrw/ajax",
    			data: '',
    			dataType: "xml",
    			complete: function(xml) {

    			},
    			success: function(xml){
                    optionsList = $('option', xml);
    				//if there are details
    				if (optionsList.size() > 0) {
                        //the div that contains the images
                        var div = document.getElementById('img_container');
                        //the it's' dimensions
                        var w = div.offsetWidth-5;
                        var h = div.offsetHeight-5;
                        //for each found subcategories
    					optionsList.each(
                            function(){
                                //the message div
                                var msg_div = document.getElementById('no_image');
                                //if it exists
                                if (msg_div){
                                    //remove it
                                    div.removeChild(msg_div);
                                }
                                //the detail image
                                var img_div = document.getElementById('detail_img');
                                //if it exists
                                if (img_div){
                                    //get image width and height
                                    var iw = this.getAttribute("width");
                                    var ih = this.getAttribute("height");
                                    //calculate ration
                                    var dimensions = calculateRatio(iw, ih, w, h);
                                    displayDetailImage(this.getAttribute("img"), dimensions['width'], dimensions['height']);
                                //if it does not exists
                                } else {
                                    //the message div
                                    var msg_div = document.getElementById('no_image');
                                    //if it exists
                                    if (msg_div){
                                        //remove it
                                        div.removeChild(msg_div);
                                    }
                                    //get image width and height
                                    var iw = this.getAttribute("width");
                                    var ih = this.getAttribute("height");
                                    //calculate ration
                                    var dimensions = calculateRatio(iw, ih, w, h);
                                    //display new image
                                    displayDetailImage(this.getAttribute("img"), dimensions['width'], dimensions['height']);
                                }
                                //if there is title
                                if (this.getAttribute("title") != ''){
                                    //the text div
                                    var txt_div = document.getElementById('detail_text');
                                    //if it exists
                                    if (txt_div){
                                        //clean the div
                                        txt_div.innerHTML = '';
                                        //create a new paragraph
                                        var par = document.createElement("p");
                                        //assign a class
                                        par.setAttribute("id", "p_b");
                                        //create a new text
                                        newText = document.createTextNode(this.getAttribute("title"));
                                        //assign the text to the paragraph
                                        par.appendChild(newText);
                                        //assign the paragraph to the div
                                        txt_div.appendChild(par);
                                        //assign a class
                                        document.getElementById('p_b').className = 'p_b';
                                    }
                                } else {
                                    //the text div
                                    var txt_div = document.getElementById('detail_text');
                                    //if it exists
                                    if (txt_div){
                                        //write empty text to it
                                        txt_div.innerHTML = '';
                                    }
                                }
                                //if there is description
                                if ($(this).text() != ''){
                                    //the text div
                                    var txt_div = document.getElementById('detail_text');
                                    //if it exists
                                    if (txt_div){
                                        //the message div
                                        var msg_div = document.getElementById('no_description');
                                        //if it exists
                                        if (msg_div){
                                            //remove it
                                            txt_div.removeChild(msg_div);
                                        }
                                        //create a new paragraph
                                        var par = document.createElement("p");
                                        //create a new text
                                        newText = document.createTextNode($(this).text());
                                        //assign the text to the paragraph
                                        par.appendChild(newText);
                                        //assign the paragraph to the div
                                        txt_div.appendChild(par);
                                    }
                                //if there is no description
                                } else {
                                    //the text div
                                    var txt_div = document.getElementById('detail_text');
                                    //if it exists
                                    if (txt_div){
                                        //if there is no title
                                        if (!this.getAttribute("title")){
                                            clearText();
                                        }
                                    }
                                }
                            }
                        );
                    //if there are no details
                    } else {
                        div = document.getElementById('img_container');
                        //the message div
                        var msg_div = document.getElementById('no_image');
                        //if it does not exists
                        if (!msg_div){
                            //the detail image
                            var img_div = document.getElementById('detail_img');
                            //if it exists
                            if (img_div){
                                //remove it
                                div.removeChild(img_div);
                            }
                            //create a new div
                            var text_div = document.createElement("div");
                            //assign an id
                            text_div.setAttribute("id", "no_image");
                            //create a new text
                            newText = document.createTextNode(messages['no_det_image'][GLOBAL_language]);
                            //assign the text to the div
                            text_div.appendChild(newText);
                            //add the div
                            div.appendChild(text_div);
                        //if it exists
                        } else {
                            //the detail image
                            var img_div = document.getElementById('detail_img');
                            //if it exists
                            if (img_div){
                                //remove it
                                div.removeChild(img_div);
                            }
                            //write the message
                            msg_div.innerHtml = messages['no_det_image'][GLOBAL_language];
                        }

                    }
                },
    			error: function(xml) {
    				alert('Error comunicating with the server (ims)!');
    			}
    		}
    	);
}

function calculateRatio(img_width, img_height, limit_width, limit_height){
    var dimensions = new Array();
    if (parseInt(img_width) >= parseInt(img_height)){
        //if the image width exceeds the div
        if (parseInt(img_width) > parseInt(limit_width)){
            //calculate width ration
            var ratio = limit_width / img_width;
            //calculate height based in width ratio
            img_height = img_height * ratio;
            dimensions['width'] = limit_width;
            dimensions['height'] = Math.round(img_height);
        //if the image width fits in the div
        } else {
            dimensions['width'] = img_width;
            dimensions['height'] = img_height;
        }
    //if image's' height > width
    } else {
        //if the image height exceeds the div
        if (parseInt(img_height) > parseInt(limit_height)){
            //calculate width ration
            var ratio = limit_height / img_height;
            //calculate height based in width ratio
            img_width = img_width * ratio;
            dimensions['width'] = Math.round(img_width);
            dimensions['height'] = limit_height;
        //if the image width fits in the div
        } else {
            dimensions['width'] = img_width;
            dimensions['height'] = img_height;
        }
    }
    return dimensions;
}

function displayDetailImage(source, image_width, image_height){
    //get the image div
    var img_div = document.getElementById('detail_img');
    //get the container
    var container = document.getElementById('img_container');
    //if image exists
    if (img_div){
        //remove any present images
        container.removeChild(img_div);
    }
    //create a new image
    var image = document.createElement("img");
    //assign a source
    image.setAttribute("src", folder+source);
    //assign an id
    image.setAttribute("id", "detail_img");
    //set dimensions
    image.setAttribute("width", image_width);
    image.setAttribute("height", image_height);
    //add the new image
    container.appendChild(image);
    //center height
    document.getElementById('detail_img').style.top = Math.round((361-image_height)/2)+'px';
    
    lodr = document.getElementById("det_loading_div");
    if (lodr){
        parN = lodr.parentNode;
        lodr.style.visibility = 'hidden';
        parN.removeChild(lodr);
    }
    //create the loading div for detail image
    var img_loading_div = document.createElement("div");
    img_loading_div.setAttribute("id", "det_loading_div");
    detLoadingText = document.createTextNode(messages['loading'][GLOBAL_language]);
    //assign the text to the div
    img_loading_div.appendChild(detLoadingText);
    //add the loading div
    container.appendChild(img_loading_div);
    //assign a class
    //document.getElementById("det_loading_div").className = 'det_loading_div';

    lodr = document.getElementById("det_loading_div");

    if (lodr){
        var det_img = document.getElementById('detail_img');
        if (det_img){
            det_img.onload = function(){
                var cont = document.getElementById('img_container');
                var lod = document.getElementById("det_loading_div");
                lod.style.visibility = 'hidden';
                cont.removeChild(lod);
            };
            det_img.onclick = function(){
                window.open('/detail.php?img='+source+'&lang='+GLOBAL_language, 'new', 'toolbar=no, scrollbars=1');
            };
        }
    }
}

function displayThumbnailImage(div_id, img_id, source, image_width, image_height, db_id){
    //get the container
    var container = document.getElementById(div_id);
    //if image exists
    if (container){
        //create a new image
        var thumb_image = document.createElement("img");
        //assign a source
        thumb_image.setAttribute("src", source);
        //assign an id
        thumb_image.setAttribute("id", img_id);
        //assign a name
        thumb_image.setAttribute("name", img_id);
        //set dimensions
        thumb_image.setAttribute("width", image_width);
        thumb_image.setAttribute("height", image_height);
        //assign the img to the div
        container.appendChild(thumb_image);
        //center height
        document.getElementById(img_id).style.top = Math.round((100-image_height)/2)+'px';
        im = document.getElementById(img_id);
        im.onclick = function(){
            changeImage(db_id);
        };
    }
}

function displayDetailMessage(){
    //get the container
    var div = document.getElementById('img_container');
    //the message div
    var msg_div = document.getElementById('no_image');
    //if it does not exists
    if (!msg_div){
        //the detail image
        var img_div = document.getElementById('detail_img');
        //if it exists
        if (img_div){
            //remove it
            div.removeChild(img_div);
        }
        //create a new div
        var text_div = document.createElement("div");
        //assign an id
        text_div.setAttribute("id", "no_image");
        //create a new text
        newText = document.createTextNode(messages['det_image'][GLOBAL_language]);
        //assign the text to the div
        text_div.appendChild(newText);
        //add the div
        div.appendChild(text_div);
    //if it exists
    } else {
        //the detail image
        var img_div = document.getElementById('detail_img');
        //if it exists
        if (img_div){
            //remove it
            div.removeChild(img_div);
        }
        //write the message
        msg_div.innerHtml = messages['det_image'][GLOBAL_language];
    }
}

function clearText(){
    //the text div
    var txt_div = document.getElementById('detail_text');
    //if it exists
    if (txt_div){
        //write empty text to it
        txt_div.innerHTML = '';
        //create a new div
        var msg_div = document.createElement("div");
        //assign an id
        msg_div.setAttribute("id", "no_description");
        //create a new text
        newText = document.createTextNode(messages['no_description'][GLOBAL_language]);
        //assign the text to the div
        msg_div.appendChild(newText);
        //add the div
        txt_div.appendChild(msg_div);
    }
}

function displayLeftMessage(mess){
    var no_thumbs = document.getElementById('no_thumbs');
    if (!no_thumbs){
        //create a new div
        var nd = document.createElement("div");
        //create a new text
        newText = document.createTextNode(messages[mess][GLOBAL_language]);
        //assign the text to the div
        nd.appendChild(newText);
        //assign a value
        nd.setAttribute("id", "no_thumbs");
        //assign the div to the parent
        document.getElementById('thumbs_list').appendChild(nd);
    } else {
        document.getElementById('no_thumbs').innerHTML = messages[mess][GLOBAL_language];
    }
}
