$(document).ready(function() {
    //Change the background image if required
    if (bg_page_path != "") {
        $('#page').css('background-image', 'url(' + bg_page_path + ')');
    }


    //calculates height of #main_copy_side
    var height_content = $('#content').height();
    var height_featured_module = $('#featured_module_large_container').height();
    var height_tweak = (10);
    if (jQuery.browser.msie && (jQuery.browser.version < 7))
        var height_tweak = (12);
    var height_total = (height_content) - (height_featured_module) - (height_tweak);
    $('#main_copy_side').css({ height: height_total });

    //Forms        
    InitInputDefaultValue(".defaultvalue_input");
    InitSubmitDefaultValue(".defaultvalue_submit", ".defaultvalue_input");


    //Expandable Modules
    InitExpandableModules();
    EventExpandableModules();

    //Properties gallery    
    $('ul.property_gallery_list').galleria({
        history: false,
        insert: '#property_gallery_main_image',
        onImage: function(image, caption, thumb) { // let's add some image effects for demonstration purposes

            // fade in the image & caption
            if (!($.browser.mozilla && navigator.appVersion.indexOf("Win") != -1)) { // FF/Win fades large images terribly slow
                //image.css('display','none').fadeIn(1000);
            }
            //caption.css('display','none').fadeIn(1000);

            // fetch the thumbnail container
            var _li = thumb.parents('li');

            // fade out inactive thumbnail
            //_li.siblings().children('img.selected').fadeTo(500,0.3);

            // fade in active thumbnail
            //thumb.fadeTo('fast',1).addClass('selected');

            // add a title for the clickable image
            image.attr('title', 'Next image >');
        },
        onThumb: function(thumb) { // thumbnail effects goes here

            // fetch the thumbnail container
            var _li = thumb.parents('li');

            // if thumbnail is active, fade all the way.
            var _fadeTo = _li.is('.active') ? '1' : '0.3';

            // fade in the thumbnail when finnished loading
            //thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);

            // hover effects
            thumb.hover(
					function() { //thumb.fadeTo('fast',1); 
					},
					function() { //_li.not('.active').children('img').fadeTo('fast',0.3); 
					} // don't fade out if the parent is active
				)
        }
    });

    //Property gallery
    initPropertyGallery();
});

//--------------------------------------------- Property Gallery
function initPropertyGallery() {
    var gallery_list = $('ul.property_gallery_list');
    var offset = 67;

    $('a.property_gallery_nav_link').click(function() {
        //$('p#debug').text($('ul.property_gallery_list').position().left); 
        //$('p#debug').append("<br/>thumbs width: " + getThumbWidth());
        return false;
    });

    //Previous
    var prev_button = true;
    $('#property_gallery_prev').mousedown(function() {
        if (prev_button == true) {
            if (parseInt(gallery_list.position().left) < 0) {
                prev_button = false;
                gallery_list.animate({
                    left: gallery_list.position().left + offset
                },
                'normal',
                function() {
                    $('p#debug').append($('ul.property_gallery_list').position().left);
                    prev_button = true;
                }
                );
            }
        }
    });

    //Next
    var next_button = true;
    $('#property_gallery_next').mousedown(function() {
        var thumbsWidth = parseInt(getGalleryThumbsWidth());
        var windowWidth = parseInt(getGalleryWindowWidth());
        var thumbsPosition = parseInt(gallery_list.position().left);

        if (next_button == true && (thumbsWidth + thumbsPosition > windowWidth)) {
            next_button = false;
            gallery_list.animate({
                left: gallery_list.position().left - offset
            },
            'normal',
            function() {
                $('p#debug').append($('ul.property_gallery_list').position().left);
                next_button = true;
            }
            );
        }
    });
    areThumbsBiggerThanWindow();
}


function scrollList(gallery_list, offset) {
    gallery_list.position().left + offset
}

function getGalleryWindowWidth() {
    return $('div.property_gallery_list_wrapper').width();
}

function getGalleryThumbsWidth() {
    var thumbs_width = 0;

    $('ul.property_gallery_list li').each(function(n) {
        thumbs_width = thumbs_width + parseInt($(this).width()) + parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
    });

    return thumbs_width;
}

function areThumbsBiggerThanWindow() {
    var window_width = $('div.property_gallery_list_wrapper').width();
    var thumbs_width = 0;

    $('ul.property_gallery_list li').each(function(n) {
        thumbs_width = thumbs_width + parseInt($(this).width()) + parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
    });

    $('p#debug').append("window width: " + window_width);
    $('p#debug').append("<br/>thumbs width: " + thumbs_width);

    if (thumbs_width > window_width) return true;
    else return false;
}

//--------------------------------------------- Expandable Modules
function InitExpandableModules() {
    //Close all modules that doesn't use the class 'open'
    $('a.exp_module_header').not('.open').find('+ div.exp_module_content').hide();
    $('a.exp_module_header').not('.open').addClass('close');
    $('a.exp_module_header').not('.open').attr('title', 'Open');
    $('a.exp_module_header.open').attr('title', 'Close');
}

function EventExpandableModules() {
    $("a.exp_module_header").click(function() {
        var link = $(this);
        var module_body = $(this).find("+ div.exp_module_content");

        module_body.slideToggle("fast", function() {
            //if the module is CLOSE and has to OPEN      
            if (module_body.css('display') == 'none') {
                link.attr('title', 'Open');
                //if the module is OPEN and has to CLOSE
            } else {
                link.attr('title', 'Close');
            }
        });
        $(this).toggleClass('close');
        $(this).toggleClass('open');

        return false;
    });
}



//--------------------------------------------- Forms
/* initialize the inputs which requires a 'default value' system */
function InitInputDefaultValue(input_class) {

    $(input_class).each(function(i) {
        var current_input_id = $(this).attr("id");
        var default_value = GetInputDefaultValue(current_input_id);
        if ($(this).val() == "") {
            $(this).val(default_value);
        }
        InitInputDefaultValueEvents("#" + current_input_id, default_value)
    });
}

/* set the focus and blur events for the 'default value' inputs */
function InitInputDefaultValueEvents(input_id, default_value) {

    $(input_id).click(function() {
        if ($(this).val() == default_value)
            $(this).val("");
    });

    $(input_id).blur(function() {
        if ($(this).val() == "")
            $(this).val(default_value);
    });
}

/* return the value of the label associated to the input */
function GetInputDefaultValue(input_id) {

    var input_default_value = "";
    $("label").each(function(j) {
        if ($(this).attr("for") == input_id) {
            input_default_value = $.trim($(this).text());
        }
    });
    return input_default_value;
}

/* clear the value of the input still using their 'default value' when the form is submitted */
function InitSubmitDefaultValue(submit_class, defaultvalue_class) {

    $(submit_class).click(function() {
        $(this).parent().find(defaultvalue_class).each(function(i) {
            var default_value = GetInputDefaultValue($(this).attr("id"));
            if ($(this).val() == default_value) {
                $(this).val("");
            }
        });
    });
}

function selectRedirect(dropdown) {
    if (dropdown.val() != '') {
        document.location.href = dropdown.val();
    }
    return false;
}



//function close_module(collapsable_module)
//{
//    bar_header = collapsable_module.prev('div.bar_header');

//    bar_header.removeClass('bar_header_current');
//    bar_header.find('p span.close').remove();
//    bar_header.find('p span').show();

//    if(collapsable_module.css('display') != 'none'){
//       collapsable_module.slideUp('fast');
//   }
//}

function includeScript(scriptUrl) {
    // Change requests to be sent synchronous
    $.ajaxSetup({ async: false });

    // Loads and executes a local JavaScript file
    $.getScript(scriptUrl);

    // Restore requests to be sent asynchronous
    $.ajaxSetup({ async: true });
} 