$(document).ready(function(){
	//	hide the openx data fetching elements:
//	$("div[class^='zone']").hide();
//	$("div[id^='sponsor']").hide();
	
    //Additional JavaScript Functions (for IE):
    if (!Array.indexOf) {
        Array.prototype.indexOf = function(obj){
            for (var i = 0; i < this.length; i++) {
                if (this[i] == obj) {
                    return i;
                }
            }
            return -1;
        };
    }
	
	//Additional JQuery Functions:
	jQuery.fn.exists = function(){return jQuery(this).length>0;}
    
    $(function(){
        $('a.lightbox').lightBox({
            imageLoading: config.baseurl + 'images/lightbox-ico-loading.gif',
            imageBtnPrev: config.baseurl + 'images/lightbox-btn-prev.gif',
            imageBtnNext: config.baseurl + 'images/lightbox-btn-next.gif',
            imageBtnClose: config.baseurl + 'images/lightbox-btn-close.gif',
            imageBlank: config.baseurl + 'images/lightbox-blank.gif'
        });
    });
    /**
     *  Selection of AHK welcome page
     */
    $(function(){
        var ahk_select = "select[name='portal']";
        $("#portal_button").click(function(){
            var ahk_selection = $(ahk_select + " option:selected").attr("value");
            if (ahk_selection !== 0) {
                if ('czech_republic' == ahk_selection) {
                    window.location = 'http://www.renewablesb2b.com/ahk_czech_republic/cs';
                }
                else {
                    window.location = 'http://' + ahk_selection + '.renewablesb2b.com';
                }
            }
        });
    });
	
    /**
     *  function to load with ajax the contact info of the chambers
     */
	var parent_element = "select[name='chamber']";
	
	function load_items(parent){
	    $.post(config.url, {
	        id: parent
	    }, function(response){
	        $("#channels").show();
	        $("#center-frame").show();
	        if (true === response.success) {
	            if (response.data.phone) {
	                $('#con_phone').html(response.data.phone);
	            }
	            else {
	                $('#con_phone').html('-');
	            }
	            if (response.data.fax) {
	                $('#con_fax').html(response.data.fax);
	            }
	            else {
	                $('#con_fax').html('-');
	            }
	            if (response.data.address) {
	                $('#con_addr').html(response.data.address);
	            }
	            else {
	                $('#con_addr').html('-');
	            }
	            if (response.data.email) {
	                $('#con_email').html('<a class="link black" href="mailto:' + response.data.email + '">' + response.data.email + '</a>');
	            }
	            else {
	                $('#con_email').html('-');
	            }
	            if (response.data.url) {
	                $('#con_url').html('<a class="link black" href="' + response.data.url + '">' + response.data.url + '</a>');
	            }
	            else {
	                $('#con_url').html('-');
	            }
	        }
	        else {
	            $('#con_phone').html('-');
	            $('#con_fax').html('-');
	            $('#con_addr').html('-');
	            $('#con_email').html('-');
	            $('#con_url').html('-');
	        }
	    }, 'json');
	}
	
	$(parent_element).change(function(){
	    var parent = [];
	    $(parent_element + " option:selected").each(function(){
	        parent.push($(this).val());
	    });
	    load_items(parent.toString());
	}).trigger('change');
    
    /**
     *  function to load with ajax the unspsc list in the products custom search form
     *  and populate the correct dropdown boxes
     */
	$(function(){
		var _fragmentHeight = 90;
		var i = 1;
		
		/**
		 * a function to set the correct height of the div that contains the products custom search form
		 * 
		 * @param {Object} _correctHeight
		 */
		function decideFragmentHeight(_correctHeight) {
			if (_fragmentHeight < _correctHeight ) {
				_fragmentHeight = _correctHeight;
				$("#fragment-3").height(_fragmentHeight);
			}
		}
		
		$("#csegment").ready(function(){
			if (-1 !== $('#csegment option:selected').attr("value")) {
				if ($('#cfamily option').length) {
					$('#cfamily-frame').show();
					decideFragmentHeight(115);
				} else {
					$('#cfamily-frame').hide();
					$('#cclass-frame').hide();
					$('#ccommodity-frame').hide();
				}
			}
		});
		
		$("#cfamily").ready(function(){
			if (-1 !== $('#cfamily option:selected').attr("value")) {
				if ($('#cclass option').length) {
					$('#cclass-frame').show();
					$("#fragment-3").height(140);
					decideFragmentHeight(140);
				} else {
					$('#cclass-frame').hide();
					$('#ccommodity-frame').hide();
				}
			}
		});
		
		$("#cclass").ready(function(){
			if (-1 !== $('#cclass option:selected').attr("value")) {
				if ($('#ccommodity option').length) {
					$('#ccommodity-frame').show();
					decideFragmentHeight(165);
				} else {
					$('#ccommodity-frame').hide();
				}
			} 
		});
		
		/**
		 * a function to fetch with ajax the correct unspsc data
		 * 
		 * @param {Object} _section
		 * @param {Object} _code
		 */
	    function loadUnspsc(_section, _code){
	        $.post(config.unspscUrl, {
	            section: _section,
	            code: _code
	        }, function(response){
	            if (true === response.success) {
	                var options = '<option value="">All</option>';
	                if (response.data) {
	                    for (unspscCode in response.data) {
	                        options += '<option value="' + unspscCode + '">' + response.data[unspscCode] + '</option>';
	                    }
	                }
	                $("#c" + _section).html(options);
	                $("#c" + _section + "-frame").show();
	                $("#c" + _section + "").show();
	            }
	            else {
	                $("#c" + _section).html('-');
	            }
	        }, 'json');
	    }
	    
		/**
		 * a fix for the dropdown lists in the ie
		 */
		if ($.browser.msie) {
			$("#csegment").width(400);
			$("#cfamily").width(400);
			$("#cclass").width(400);
			$("#ccommodity").width(400);
		}
	    $("#csegment").change(function(){
	        var _selectedCode = [];
	        $("#csegment option:selected").each(function(){
	            _selectedCode.push($(this).val());
	        });
	        if ('' == _selectedCode.toString()) {
	            $("#cfamily-frame").hide();
	            $("#cclass-frame").hide();
	            $("#ccommodity-frame").hide();
	            $("#cfamily").hide();
	            $("#cfamily").html('<option value=""></option>');
	            $("#cclass").hide();
	            $("#cclass").html('<option value=""></option>');
	            $("#ccommodity").hide();
	            $("#ccommodity").html('<option value=""></option>');
	            $("#fragment-3").animate({
	                height: "90px"
	            });
	        }
	        else {
				$("#cclass-frame").hide();
	            $("#ccommodity-frame").hide();
				$("#cclass").hide();
				$("#cclass").html('<option value=""></option>');
	            $("#ccommodity").hide();
	            $("#ccommodity").html('<option value=""></option>');
	            loadUnspsc('family', _selectedCode.toString());
	            $("#fragment-3").animate({
	                height: "115px"
	            });
	        }
	    });
	    
	    $("#cfamily").change(function(){
	        var _selectedCode = [];
	        $("#cfamily option:selected").each(function(){
	            _selectedCode.push($(this).val());
	        });
	        if ('' == _selectedCode.toString()) {
	            $("#cclass-frame").hide();
	            $("#ccommodity-frame").hide();
	            $("#cclass").hide();
	            $("#cclass").html('<option value=""></option>');
	            $("#ccommodity").hide();
	            $("#ccommodity").html('<option value=""></option>');
	            $("#fragment-3").animate({
	                height: "115px"
	            });
	        }
	        else {
				$("#ccommodity-frame").hide();
				$("#ccommodity").hide();
				$("#ccommodity").html('<option value=""></option>');
	            loadUnspsc('class', _selectedCode.toString());
	            $("#fragment-3").animate({
	                height: "140px"
	            });
	        }
	    });
	    
	    $("#cclass").change(function(){
	        var _selectedCode = [];
	        $("#cclass option:selected").each(function(){
	            _selectedCode.push($(this).val());
	        });
	        if ('' == _selectedCode.toString()) {
	            $("#ccommodity-frame").hide();
	            $("#ccommodity").hide();
	            $("#ccommodity").html('<option value=""></option>');
	            $("#fragment-3").animate({
	                height: "140px"
	            });
	        }
	        else {
	            loadUnspsc('commodity', _selectedCode.toString());
	            $("#fragment-3").animate({
	                height: "165px"
	            });
	        }
	    });
    });
    
    
    
    /*
     $(function() {
     var parent_element	= "a[name='captchaReload']";
     var post_file		= config.url2;
     
     $(parent_element).click(function(){
     var parent = new Array();
     $(parent_element+" option:selected").each(function(){parent.push($(this).val());});
     load_items(parent.toString());
     }).trigger('change');
     
     function load_items(parent) {
     $.post(post_file, {id:parent},
     function(response) {
     $("#channels").show();
     $("#center-frame").show();
     if(response.success == true) {
     if (response.data.phone) $('#con_phone').html(response.data.phone); else $('#con_phone').html('-');
     if (response.data.fax) $('#con_fax').html(response.data.fax); else $('#con_fax').html('-');
     if (response.data.address) $('#con_addr').html(response.data.address); else $('#con_addr').html('-');
     if (response.data.email) $('#con_email').html('<a class="link black" href="mailto:'+response.data.email+'">'+response.data.email+'</a>'); else $('#con_email').html('-');
     if (response.data.url) $('#con_url').html('<a class="link black" href="'+response.data.url+'">'+response.data.url+'</a>'); else $('#con_url').html('-');
     } else {
     $('#con_phone').html('-');
     $('#con_fax').html('-');
     $('#con_addr').html('-');
     $('#con_email').html('-');
     $('#con_url').html('-');
     }
     },
     'json'
     );
     }
     });
     */
//    var parent_element = "select[name='chamber']";
    
    $(function(){
        $(".textField.blue").focus(function(){
            $(this).toggleClass("focused-blue");
        });
        $(".textField.blue").blur(function(){
            $(this).toggleClass("focused-blue");
        });
    });
    
    $(function(){
        $(".blue-theme").focus(function(){
            $(this).toggleClass("focused-blue-theme");
        });
        $(".blue-theme").blur(function(){
            $(this).toggleClass("focused-blue-theme");
        });
    });
    
    /**
     * Initial selection for welcome page if locale is detected
     */
    $(function(){
        var ahk_select = "select[name='portal']";
        var locale_detection = $("#detected_country").attr("value");
        $(ahk_select + " option[value=" + locale_detection + "]").attr('selected', 'selected');
    });
    
    
    $(function(){
        $("a.tooltip").tooltip({
            bodyHandler: function(){
                return $(this).attr("value");
            },
            showURL: false
        });
    });
    $(function(){
        $("img.tooltip").tooltip({
            bodyHandler: function(){
                return $(this).attr("value");
            },
            showURL: false
        });
    });
    $(function(){
        $("span.tooltip").tooltip({
            bodyHandler: function(){
                return $(this).attr("value");
            },
            showURL: false
        });
    });
    
    $(function(){
        $("a.description_tooltip").description_tooltip({
            bodyHandler: function(){
                return $(this).attr("value");
            },
            showURL: false
        });
    });
    
    $("#tabs").show();
    $("#channels").show();
    $("#sections").show();
    $("#marketplace_channels").show();
    $("#marketplace_sections").show();
    $("#center-frame").show();
    $("#marketplace-center-frame").show();
    
    $("#timeline_menu").change(function(){
        if (this.value) {
            document.location = this.value;
        }
        //		document.timeline_menu.options[document.timeline_menu.selectedIndex].value
    });
    
    $("#printlink").click(function(){
        if (this.rel) {
            window.open('<?=$this->baseUrl()?>print.php?obj=' + this.rel, 'printwindow', 'width=535,height=600,scrollbars=yes,resizable=yes');
        }
    });
    
    $("#finalprintlink").click(function(){
        window.print();
    });
    
    $(function(){
        var channel = null;
        var section = null;
        var title = $('#title-frame').text();
        
        $('#channels a.selected').each(function(){
            channel = $(this).attr("id");
            title = $(this).attr("name");
            $('#title-frame').text(title);
        });
        $('#channels a').mouseout(function(){
            if ($(this).attr("id") != channel) {
                $(this).toggleClass("selected");
            }
            $('#title-frame').text(title);
            return false;
        });
        $('#channels a').mouseover(function(){
            if ($(this).attr("id") != channel) {
                $(this).toggleClass("selected");
            }
            $('#title-frame').text($(this).attr("name"));
            return false;
        });
        
        $('#sections a.selected').each(function(){
            section = $(this).attr("id");
        });
        $('#sections a').mouseout(function(){
            if ($(this).attr("id") != section) {
                $(this).toggleClass("selected");
            }
            return false;
        });
        $('#sections a').mouseover(function(){
            if ($(this).attr("id") != section) {
                $(this).toggleClass("selected");
            }
            return false;
        });
        
        
    });
    
    $(function(){
        var channel = null;
        var marketplace_section = null;
        var title = $('#title-frame').text();
        
        $('#marketplace_channels a.selected').each(function(){
            channel = $(this).attr("id");
            title = $(this).attr("name");
            $('#title-frame').text(title);
        });
        $('#marketplace_channels a').mouseout(function(){
            if ($(this).attr("id") != channel) {
                $(this).toggleClass("selected");
            }
            $('#title-frame').text(title);
            return false;
        });
        $('#marketplace_channels a').mouseover(function(){
            if ($(this).attr("id") != channel) {
                $(this).toggleClass("selected");
            }
            $('#title-frame').text($(this).attr("name"));
            return false;
        });
        
        $('#marketplace_sections a.selected').each(function(){
            marketplace_section = $(this).attr("id");
        });
        $('#marketplace_sections a').mouseout(function(){
            if ($(this).attr("id") != marketplace_section) {
                $(this).toggleClass("selected");
            }
            return false;
        });
        $('#marketplace_sections a').mouseover(function(){
            if ($(this).attr("id") != marketplace_section) {
                $(this).toggleClass("selected");
            }
            return false;
        });
    });
    
    $('#cdate_from').datepicker($.extend({},    //$.datepicker.regional["el"], 
    {
        showOn: "focus",
        changeFirstDay: false,
        yearRange: "-10:+0",
        buttonText: "",
        buttonImageOnly: true
    }));
    $('#cdate_to').datepicker($.extend({},    //$.datepicker.regional["el"], 
    {
        showOn: "focus",
        changeFirstDay: false,
        yearRange: "-10:+0",
        buttonText: "",
        buttonImageOnly: true
    }));
    $(".select-content > select option").each(function(){
        $(this).attr("title", $(this).html());
    });
    
    /**
     * populate the div with id selected_companies with the companies
     * that are stored in the session
     *
     * @return void
     */
    function showSelectedCompanies(){
        $.post(config.selectedcompanies, {
            "request": true
        }, function(response){
            if ($("#selected_companies").is(":hidden")) {
                $("#selected_companies").slideDown("slow");
            }
            if (true === response.success) {
                if (response.data) {
                    $("#selected_companies").html(response.data);
                }
                else {
                    $("#selected_companies").html('-');
                }
            }
            else {
                $("#selected_companies").html('-');
            }
            $(".selected_company").ready(function(){
                jQuery.each($(".selected_company"), function(){
                    $("#" + $(this).attr("id") + "_checkbox").attr('checked', true);
                });
            });
            $(".selected_company").click(function(){
                var company_data = $(this).attr("rel");
                $.post(config.removecompany, {
                    "company_data": company_data
                });
                $("#" + $(this).attr("id") + "_checkbox").attr('checked', false);
                showSelectedCompanies();
            });
        }, 'json');
    }
    
    /**
     * add in or remove from the session the company's id
     *
     * @param string element
     * @return void
     */
    function toggleCompany(element){
        var company_data = $(element).attr("value");
        if (false === $(element).attr('checked')) {
            $.post(config.removecompany, {
                "company_data": company_data
            });
        }
        else {
            $.post(config.addcompany, {
                "company_data": company_data
            });
        }
    }
    
    if (document.location.href.indexOf('companies/list') != -1) {
        showSelectedCompanies();
    }
    
    $(".message_checkbox").click(function(){
        toggleCompany(this);
        showSelectedCompanies();
    });
    
    $("#check_all").click(function(){
        $(".message_checkbox").attr('checked', true);
        jQuery.each($(".message_checkbox"), function(){
            toggleCompany(this);
        });
        showSelectedCompanies();
    });
    $("#uncheck_all").click(function(){
        $(".message_checkbox").attr('checked', false);
        jQuery.each($(".message_checkbox"), function(){
            toggleCompany(this);
        });
        showSelectedCompanies();
    });
    
    $("#select_company_action").click(function(){
        if ('send_message' == $("#select_company_action option:selected").attr("id")) {
            $.post(config.sendmessage, {
                "request": true
            }, function(response){
                if (true === response.success) {
                    if (response.data) {
                        window.location = response.data;
                    }
                }
            }, 'json');
        }
    }).trigger('click');
    
    /**
     * return the answer of a faq
     */
    $(".faq_question").click(function(){
        $(".faq_selected").toggleClass("faq_selected");
        $(this).toggleClass("faq_selected");
        
        $.post(config.getFaqAnswer, {
            "question_id": $(this).attr("value"),
            "language": $(this).attr("rel")
        }, function(response){
            if (true === response.success) {
                if (response.answer) {
                    if ($("#answer").is(":hidden")) {
                        $("#answer").slideDown(400, function(){
                            $("#faq_answer").html(response.answer);
                        });
                    }
                    else {
                        $("#answer").fadeOut(300, function(){
                            $("#faq_answer").html(response.answer);
                        });
                        $("#answer").fadeIn(400);
                    }
                }
                else {
                    if ($("#answer").is(":visible")) {
                        $("#answer").slideUp(400);
                    }
                }
            }
            else {
                if ($("#answer").is(":visible")) {
                    $("#answer").slideUp(400);
                }
            }
        }, 'json');
    });
    
});
