// Subject to frequent change

$(document).ready( function() {

    //Show all comment fields.
    $(".post-comment-container").fadeIn("fast"); 

    //Initialize modal.
    init_modal();

    //Radio button redesign.
    $("form input[type='radio']").css("display", "none");
    $("form input[type='radio']:checked").parent("label").addClass("input-selected");

    $(".radiobutton label:first-child").css({
        'border-width': '1px 1px 1px 1px',
        'border-top-left-radius': '3px',
        'border-bottom-left-radius': '3px'
    });

    $(".radiobutton label:last-child").css({
        'border-width': '1px 1px 1px 0',
        'border-top-right-radius': '3px',
        'border-bottom-right-radius': '3px'
    });

    $("form input[type='radio']").click( function(e){
        
        var label = $(this).parent("label");
        var name = $(this).attr("name");

        if (!label.hasClass("input-selected")) {

/*            $("input[name='" + name + "']").parent("label").parent("label").animate({
                opacity: 0.4
            }, 1000);*/

            $("input[name='" + name + "']").parent("label").removeClass("input-selected");
            $("input[name='" + name + "']").attr("checked", false);
            $(this).parent("label").addClass("input-selected");
            $(this).attr("checked", true);
        }
    });

    //Select button redesign.
    var selectElements = $("form select");

    selectElements.css({
        'position': 'relative',
        'opacity': '0',
        '-moz-opacity': '0',
        'filter': 'alpha(opacity: 0)',
        'z-index': 2
    });

    //var selectWidth = selectElements.width();
    selectElements.parent().css({
        "position": "relative"
    });
    
    selectElements.parent().append('<div class="select-fake"></div><div class="arrow-down"></div>');

    selectElements.each(function(){
       var selectedText = $(this).find("option:selected").html();
       var selectWidth = $(this).width();
       if (selectWidth == 0) {
           selectWidth = 280;
       }
       var selectFake = $(this).parent().find(".select-fake")
       selectFake.html(selectedText);
       selectFake.css("width", selectWidth);

       $(this).change(function(e){
           var newValue = $(e.target).find("option:selected").html();
           selectFake.html(newValue);
       });

       $(this).mouseover(function(){
           selectFake.addClass("select-fake-over");
       });
       $(this).mouseout(function(){
           selectFake.removeClass("select-fake-over");
       });

    });

    $('iframe').each(function(){
        var url = $(this).attr("src");
        $(this).attr("src",url+"?wmode=transparent");
    });

});

function initMediaLoader () {

    var elements =  {
        itemClass: ".uploader-item",
        imageButtonId: "#post-image-button",
        videoButtonId: "#post-video-button",
        mapButtonId: "#post-map-button",
        imageUploaderId: "#post-image-uploader",
        videoUploaderId: "#post-video-uploader",
        mapUploaderId: "#post-map-uploader"
    };

    //setDefaultText("#friend-email", "Email");
    wjInterfaceComponents.imageUploader();
//    wjInterfaceComponents.toolTip();

    $(elements.imageButtonId).click(function(){
        $(elements.itemClass).hide();
        $(elements.imageUploaderId).fadeIn();
    });

    //Hack for input file=type button design.
    $("#post-image-uploader-button").mouseover( function(){
        $("#post-image-uploader-fakebutton").addClass("over")
        
        /*    .css({'color': '#ffffff',
                  'border': 'solid 1px #ff6699',
                  'background-color': '#ff6699'});*/
        $(this).css('cursor', 'pointer');
    });
    
    $("#post-image-uploader-button").mouseout( function(){
        $("#post-image-uploader-fakebutton").removeClass("over");        
            /*.css({
                  'border': 'solid 1px #0099ff',
                  'background-color': '#0099ff'});*/
    });

    $("#post-video-button").click(function(){
        $(".uploader-item").hide();
        $("#post-video-uploader").fadeIn();
    });
    init_videoUploader();

    setDefaultText('#uploader-video-source', 'Paste video source url...');

    $("#post-map-button").click(function(){
        $(".uploader-item").hide();
        $("#post-map-uploader").fadeIn();
        initializeMap('uploader-map-canvas');
    });

    setDefaultText('#uploader-map-address', 'Type address here...');

    $.mb_videoEmbedder.defaults.width = 500; //the width of players --> the height is automatically calculated
    $('#uploader-video-embed').mb_embedMovies();
    //$('#example').mb_mb_embedAudio();

}

//(function imageUploader( $ ){

var wjInterfaceComponents = {

    toolTip: function() {
        var setting;
        
        var method = {
            init: function(e){},
            start: function(e){},
            complete: function(r){}
        };

        $.fn.tooltip = function(o) {

            setting = {
                'init': method.init,
                'start': method.start,
                'complete': method.complete,
                'text': 'tooltip'
            };

            this.each( function(){
                if(o) $.extend(setting, o);
                var targetField = $(this);

                targetField.bind('mouseover', function(e){

                    //Append the tooltip template and its value
                    targetField.prepend('<div id="tooltip" style="display: none;"><div class="tipHeader"></div><div class="tipBody">' + setting.text + '</div><div class="tipFooter"></div></div>');

                    //Show the tooltip with faceIn effect
                    $('#tooltip').fadeIn('500');
                    $('#tooltip').fadeTo('10',0.9);
                });

                targetField.bind('mousemove', function(e) {
                    //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
                    $('#tooltip').css('top', e.pageY - 50);
                    $('#tooltip').css('left', e.pageX + 10);
                });

                targetField.bind('mouseout', function(e) {
                    //Remove the appended tooltip template
                    targetField.children('div#tooltip').remove();
                });
            });          
        }
    },

    // Image Drag-Drop Uploader by Goker Cebeci.
    // http://gokercebeci.com/dev/droparea
    // http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html

    imageUploader: function() {

        var s;
        // Methods
        var m = {
            init: function(e){},
            start: function(e){},
            complete: function(r){},
            error: function(r){alert(r.error);return false;},
            traverse: function(files,area){
                if (typeof files !== "undefined") {
                    for (var i=0, l=files.length; i<l; i++) {
                        m.upload(files[i], area);
                    }
                } else {
                    area.html("nosupport");
                }
            },
            upload: function(file, area){
                //area.empty();
                var progress = $('<div>',{
                    'class':'progress'
                });
                area.append(progress);

                // Uploader support control
                if (typeof FileReader === "undefined") {
                    // means no dragdrop
                    //alert('No supported (fixing this now)');
                    //return false;
                }

                // File type control
                if (!(/image/i).test(file.type)) {

                    alert('only image files: jpeg, png, gif and bmp');
                    return false;
                }

                // File size control
                if (file.size > (s.maxsize * 1024)) {
                    //area.html(file.type,s.maxsize);
                    alert('max upload size: ' + s.maxsize + 'Kb');
                    return false;
                }

                // Uploading - for Firefox, Google Chrome and Safari
                //testing for Safari 5
                //http://www.deadmarshes.com/Blog/20110413023355.html

                var xhr = new XMLHttpRequest();
                // Update progress bar
                xhr.upload.addEventListener("progress", function (e) {
                    if (e.lengthComputable) {
                        var loaded = Math.ceil((e.loaded / e.total) * 100) + "%";
                        progress.css({
                            'height':loaded
                        }).html(loaded);
                    }
                }, false);

                // File uploaded
                // Call back after load completion
                xhr.addEventListener("load", function (e) {
                    var r = jQuery.parseJSON(e.target.responseText);
                    s.complete(r);
                    area.find('img').remove();
                    //area.data('value',r.filename)
                    //.append($('<img>',{'src': r.path + r.filename + '?' + Math.random()}));
                    area.append('<img class="post-uploader-image-preview" src="' + r.path + '/' + r.previewFilename + '"/>');
                    progress.addClass('uploaded');
                    progress.html(s.uploaded).fadeOut('slow');
                    //Save image path to hidden form elements
                    //$("#newPost").find("#image").val(r.path + '/' + r.filename);

                }, false);

                xhr.open("post", s.post, true);

                // Set appropriate headers
                xhr.setRequestHeader("Content-Type", "multipart/form-data");
                xhr.setRequestHeader("X-File-Name", file.fileName);
                xhr.setRequestHeader("X-File-Size", file.fileSize);
                xhr.setRequestHeader("X-File-Type", file.type);

                // Set request headers
                for (var i in area.data())
                    if (typeof area.data(i) !== "object")
                        //Change capital letter to uppercase
                        //xhr.setRequestHeader('X-Param-'+i, area.data(i));
                        xhr.setRequestHeader('X-Param-' + i.charAt(0).toUpperCase() + i.slice(1), area.data(i));

                xhr.send(file);
            }
        };

        $.fn.droparea = function(o) {
            // Settings
            s = {
                'init': m.init,
                'start': m.start,
                'complete': m.complete,
                'instructions'    : 'Drop an image file here',
                'instructionsIE'  : 'Image can be previewed here',
                'over'            : 'Drop file here!',
                'nosupport'       : 'No support for the File API in this web browser',
                'noimage'         : 'Unsupported file type!',
                'uploaded'        : 'Uploaded',
                'maxsize'         : '5000', //Kb
                'post'            : 'upload.php',
                'uploadButtonName': 'post-image-uploader-button',
                'dropAreaId'      : 'post-image-uploader-droparea'
            };

            this.each( function(){
                if(o) $.extend(s, o);
                $(this).append('<div id="droparea-instructions"></div>');
                //var instructions = $('<div>').appendTo($(this));
                var instructions = $('#droparea-instructions');

                var isMSIE = /*@cc_on!@*/false;
                if (isMSIE === true) {
                    s.instructions = s.instructionsIE;
                }

                s.init($(this));
                if(!$(this).data('value'))
                    instructions.addClass('instructions').html(s.instructions);

                //Better skip this for IE
                //alert(isMSIE);
                if (isMSIE === false) {
                    $(this).bind({
                        dragleave: function (e) {
                            e.preventDefault();
                            if($(this).data('value'))
                                //instructions.removeClass().empty();
                                $('#droparea-instructions').removeClass().empty();
                            else
                                //instructions.removeClass('over').html(s.instructions);
                                $('#droparea-instructions').removeClass('over').html(s.instructions);
                        },
                        dragenter: function (e) {
                            e.preventDefault();
                            //instructions.addClass('instructions over').html(s.over);
                            $('#droparea-instructions').addClass('instructions over').html(s.over);
                        },
                        dragover: function (e) {
                            e.preventDefault();
                        }
                    });

                    this.addEventListener("drop", function (e) {
                        e.preventDefault();
                        s.start($(this));
                        m.traverse(e.dataTransfer.files, $(this));
                        //instructions.removeClass().empty();
                        $('#droparea-instructions').removeClass().empty();
                    },false);

                } else {
                    // Do something if necessary
                }

            });

            var uploadButton = $("#" + s.uploadButtonName);
            uploadButton.change(function(e){
                /*s.start($("#post-image-uploader-droparea"));
                m.traverse(e.currentTarget.files, $("#post-image-uploader-droparea"));
                $("#post-image-uploader-droparea").find(".instructions").removeClass().empty();*/
                s.start($("#" + s.dropAreaId));
                m.traverse(e.currentTarget.files, $("#" + s.dropAreaId));
                $("#" + s.dropAreaId).find(".instructions").removeClass().empty();
            });
        };
    }
}

//imageUploader();
//})( jQuery );

//http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-mediaembedder/

function init_videoUploader() {

    $("#uploader-video-source").bind('keypress', function(e){
        if (e.which == "13" ) {
            e.preventDefault();
            previewVideo('uploader-video-embed');
        }
    });

}

function previewVideo(target) {

    //[vimeo=http://www.vimeo.com/109467]
    //http://www.ustream.tv/channel/iwakamiyasumij

    var videoUrl = $("#uploader-video-source").val();
    var videoMeta = parseVideoURL(videoUrl);

    if (videoMeta.provider === "youtu") {
        videoMeta.provider = "youtube";
        videoUrl = "http://youtube.com/watch?v=" + videoMeta.id;
    }
    $("#uploader-video-url").val(videoUrl);
    $("#" + target).html('[' + videoMeta.provider + '=' + videoUrl + ']');
    $("#" + target).mb_embedMovies();
    //Error handling needed
    $("#newPost").find("#videoType").val(videoMeta.provider);
    $("#newPost").find("#video").val(videoMeta.id);
}

//Thanks to the author of this code
//http://stackoverflow.com/questions/5612602/improving-regex-for-parsing-youtube-vimeo-urls
function parseVideoURL(url) {

    var provider = url.match(/http:\/\/(:?www.)?(\w*)/)[2],
        id;

    if(provider == "youtube") {
        id = url.match(/http:\/\/(?:www.)?(\w*).com\/.*v=(\w*)/)[2];
    } else if (provider == "youtu") {
        
        id = url.match(/http:\/\/(?:www.)?(\w*).be\/(\w*)/)[2];
    } else if (provider == "vimeo") {

        id = url.match(/http:\/\/(?:www.)?(\w*).com\/(\d*)/)[2];
    } else if (provider == "ustream") {
        //subject to change.
        id = url.match(/http:\/\/(?:www.)?(\w*).com\/(\d*)/)[2];
    } else {
        throw new Error("parseVideoURL() takes a YouTube or Vimeo URL");
    }
    return {
        provider : provider,
        id : id
    }
}

// Google Maps

var geocoder;
var maps = [];

function initializeMap(canvasId) {

    var initialLocation = new google.maps.LatLng(35.682946, 139.686907);

    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }

    var stylez = [
        {
            featureType: "all",
            elementType: "geometry",
            stylers: [{
            hue: "#0099ff"
            },{
            saturation: 10
            },{
            lightness: 20
            }]
        }];

    var myOptions = {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.TERRAIN,//ROADMAP
        scrollwheel: false
    }
    
    var map = new google.maps.Map(document.getElementById(canvasId), myOptions);
    maps.push(map);

    // Try W3C Geolocation (Preferred)
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            map.setCenter(initialLocation);
        });
    // Browser doesn't support Geolocation
    } else {
        map.setCenter(initialLocation);;
    }

    var styledMapOptions = {
        map: map,
        name: "wj-map"
    }

    var wjMapType = new google.maps.StyledMapType(stylez, styledMapOptions);

    map.mapTypes.set('wj-map', wjMapType);
    map.setMapTypeId('wj-map');

    $("#uploader-map-address").bind('keypress', function(e){
        if (e.which == "13" ) {
            e.preventDefault();
            codeAddress('uploader-map-address');
        }
    });
}

var marker;

function codeAddress(id) {

    var map = maps[0];

    addressField = $("#" + id);

    if (addressField.hasClass("default-text")) {
        return;
    } else if (addressField.val() === "") {
        return;
    }

    var address = document.getElementById(id).value;
    if (geocoder) {
        geocoder.geocode( {'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                if(marker !== undefined) {
                    marker.setMap();
                }

                map.setCenter(results[0].geometry.location);
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                var latlong = map.getCenter();
                $("#newPost").find("#mapLat").val(latlong.lat());
                $("#newPost").find("#mapLong").val(latlong.lng());
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
}

function addMap(canvasId, coordinate) {

    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }

    if (!coordinate.lat || !coordinate.lng) {
        return;
    }

    var latlng = new google.maps.LatLng(coordinate.lat, coordinate.lng);
    //var latlng = new google.maps.LatLng(-34.397, 150.644);

    var stylez = [
        {
            featureType: "all",
            elementType: "geometry",
            stylers: [{
            hue: "#0099ff"
            },{
            saturation: 10
            },{
            lightness: 20
            }]
        }];

    var myOptions = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.TERRAIN,//ROADMAP
        scrollwheel: false
    }
    var map = new google.maps.Map(document.getElementById(canvasId), myOptions);
    //maps.push(map);

    var tooltip = "Latitude: " + coordinate.lat + " Longitude: " + coordinate.lng;

    var markerPin = new google.maps.Marker({
        position: latlng,
        map: map,
        title: tooltip
    });

    var styledMapOptions = {
        map: map,
        name: "wj-map"
    }

    var wjMapType = new google.maps.StyledMapType(stylez, styledMapOptions);

    map.mapTypes.set('wj-map', wjMapType);
    map.setMapTypeId('wj-map');   

}

function addMemberMap(canvasId, placeList, zoom, imageUrl) {

    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }
    
    var port = window.location.port;
    if (port != '') {
            port = ':'+port;
    }
    var baseUrl = window.location.protocol+'//'+window.location.hostname+port;

    if (imageUrl) {
        // Default marker image
        console.log('Map icon url: ' + imageUrl);
        var imageMarker = new google.maps.MarkerImage(
            imageUrl, 
            new google.maps.Size(15, 19),
            new google.maps.Point(0, 0),
            new google.maps.Point(8, 2)
        );
    }
    var coordinate = {'lat':20.00000, 'lng':11.5801863};
    var latlng = new google.maps.LatLng(coordinate.lat, coordinate.lng);
    //var latlng = new google.maps.LatLng(-34.397, 150.644);

    var stylez = [
        {
            featureType: "all",
            elementType: "geometry",
            stylers: [{
            hue: "#0099ff"
            },{
            saturation: 10
            },{
            lightness: 20
            }]
        }];

    var myOptions = {
        zoom: zoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.SATELLITE, //TERRAIN,//ROADMAP
        scrollwheel: false,
        streetViewControl: false,
        mapTypeControl: false,
        navigationControl: true,
        navigationControlOptions: {
            position: google.maps.ControlPosition.LEFT_BOTTOM
        }
    }
    var map = new google.maps.Map(document.getElementById(canvasId), myOptions);
    //maps.push(map);
    var count = 1;

    for(var i in placeList) {         
        // Limit country markers up to 12 until we get a lat/long database.
        if (count < 13) {
            geocoder.geocode( {'address': placeList[i]}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    //if(marker !== undefined) {
                      //  marker.setMap();
                    //}

                    //map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        icon: imageMarker
                    });
                    //var latlong = map.getCenter();
                } else {
                    //alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }
        count++;
    }

    var styledMapOptions = {
        map: map,
        name: "wj-map"
    }

    var wjMapType = new google.maps.StyledMapType(stylez, styledMapOptions);

    map.mapTypes.set('wj-map', wjMapType);
    map.setMapTypeId('wj-map');

}

//Handy functions
function setDefaultText(id, text) {

        var field = $(id);
        var defaultTextClass = "default-text";

        if (field.val() == "")
        {
            field.val(text);
            //Lets define defaultTextActive class in css.
            field.addClass(defaultTextClass);
        } else if (field.val() == text) {
            field.addClass(defaultTextClass);
        } else {
            field.removeClass(defaultTextClass);
        }

        field.focus(function() {
           if ($(this).hasClass(defaultTextClass))
           {
               $(this).removeClass(defaultTextClass);
               $(this).val("");
           }
        });

        field.blur(function(){
           if ($(this).val() == "")
           {
               $(this).addClass(defaultTextClass);
               $(this).val(text);
           }
        });
        field.blur();
}

function setToolTip(element, text) {

    var targetField = element;

    targetField.bind('mouseover', function(e){
    //$(this).addClass("mouseOver");
        //Append the tooltip template and its value
        targetField.prepend('<div id="tooltip" style="display: none"><div class="tipHeader"></div><div class="tipBody">' + text + '</div><div class="tipFooter"></div></div>');

        //Show the tooltip with faceIn effect
        $('#tooltip').fadeIn('500');
        $('#tooltip').fadeTo('10',0.9);
    });

    targetField.bind('mousemove', function(e) {
        //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
        $('#tooltip').css('top', e.pageY - 50);
        $('#tooltip').css('left', e.pageX + 10);
    });

    targetField.bind('mouseout', function(e) {
        //Remove the appended tooltip template
        targetField.children('div#tooltip').remove();
        //$(this).removeClass("mouseOver");
        //$(this).css("background-color", "transparent");

    });
}

// First version for modal screen.

// Initialize.
function init_modal() {

//temp
    var port = window.location.port;
    if (port != '') {
            port = ':'+port;
    }
    var baseUrl = window.location.protocol+'//'+window.location.hostname+port;
    
    // Does element exist?
    if (!$('a.modal').length && !$('.button-modal').length) {
        // If not, exit.
        return;
    }
    // Detect IE6 (boolean).
    var $IE6 = typeof document.addEventListener !== 'function' && !window.XMLHttpRequest;

    function sizeModal(target) {
    // Modal dimensions.
        var $modal = $(target).find('.modal_window');
        var $modal_width = $modal.outerWidth();
        var $modal_height = $modal.outerHeight();
        var $modal_top = '-' + Math.floor($modal_height / 2) + 'px';
        var $modal_left = '-' + Math.floor($modal_width / 2) + 'px';
        // Set modal.
        $('.modal_window').css('margin-top', $modal_top).css('margin-left', $modal_left);
    }

    /* For IE6. */
    function positionModal() {
        // Force modal into place.
        $('.modal_wrapper').css('top', $(document).scrollTop() + 'px');
    }

    // Reveal the modal.
    function showModal(link, title) {
        if ($IE6) {
            positionModal();
        }
        
        // Reveal static content
        if (link.match(/^#./)) {
            $(link).fadeIn();
        // Assuming ajax content
        } else {
            $.get(link, function(data){
                var content = {title: title, content: data};
                var ajax = $("#modal-template").tmpl(content);          
                $('body').append($(ajax));
                $('.modal_ajax').fadeIn('fast', function(){                   
                    sizeModal('.modal_ajax');
                    if (facebook_client.get("page_id")) {
                        $('.modal_window').css('width', '420px').css('margin-top', '0').css('top', '20px');
                    }
                    $('.modal_window').css('visibility', 'visible').show(); 

                });
                  
                $('.modal_ajax').find(".modal_overlay, .modal_close").click(function(){
                    $('.modal_ajax').remove();
                    this.blur();
                    return false;
                });
            });
        }

        // Size it.
        sizeModal(link);

        // Reveal modal window.
        $('.modal_window').css('visibility', 'visible').show();

        // Resize as images load.
        $('.modal_content img').each(function() {
            $(this).load(function() {$(this).removeClass('modal_placeholder').show();
                sizeModal();
            });
        });
    }

    // Insert modal at end of </body>.
    //$('body').append('<div id="modal_wrapper"><!--[if IE 6]><iframe id="modal_iframe"></iframe><![endif]--><div id="modal_overlay"></div><div id="modal_window"><div id="modal_bar"><h1>Modal window</h1><a href="#" id="modal_close"><img width="14" src="' + baseUrl + '/images/default/i_close.png"/></a></div><div id="modal_content"></div></div>');

    // Look for modal links.
    $('.button-modal').click(function() {

        // Check the href="..."
        var link = $(this).attr('href');
        var title = $(this).attr('title')

        // Determine link target.
        showModal(link, title);
        /*
        if ($the_link.match(/^#./)) {
            // Assume #anchor content.
            // Binding events may face problems.
            //$('#modal_content').html($($(this).attr('href')).html());
            showModal($the_link);
            // Add event handlers
            //bindEvents();
        } else if ($the_link.match(/.jpg$/) || $the_link.match(/.png$/) || $the_link.match(/.gif$/)) {
            // Assume image content.
            $('.modal_content').html('<p id="modal_image_wrapper"> <img src="' + $the_link + '" class="modal_placeholder" /></p> ');
            showModal('');
        } else {
            // Assume external Ajax content.
            //$('.modal_content').load($(this).attr('href').replace('#', ' #'), '', showModal);
        }*/

        // Determine modal title.
        if ($(this).attr('title')) {
            // Insert title.
            $('.modal_bar h1').html($(this).attr('title'));
        } else if ($(this).html() !== '') {
            // Insert link text.
            $('.modal_bar h1').html($(this).html());
        }
        // Nofollow.
        this.blur();
        return false;
    });

    // Hide modal elements.
    $('.modal_overlay, .modal_close').click(function() {
        // Hide the modal.
        $('.modal_wrapper').hide();
        // Hide, because images might load later.
        $('.modal_window').css('visibility', 'hidden');

        // Unbind image listeners.
        $('.modal_content img').each(function() {
            $(this).unbind();
        });
        // Destroy modal content.
        //$('#modal_content').html('');
        
        // Reset modal title.
        $('.modal_bar strong').html('Modal window');
        // Nofollow.
        this.blur();
        return false;
    });  

    // Listen for browser scroll, if IE6.
    if ($IE6) {
        $(window).scroll(function() {
            if ($('.modal_wrapper').is(':visible')) {
                positionModal();
            }
        });
    }
}
