var RESOURCES_PATH = "/system/modules/ro.grapefruit.relians.website/resources";
var ZINDEX_TOPMOST = 1000;
var LIGHTBOX_OPTIONS = {
    imageLoading:			RESOURCES_PATH+'/images/lightbox/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
    imageBtnPrev:			RESOURCES_PATH+'/images/lightbox/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
    imageBtnNext:			RESOURCES_PATH+'/images/lightbox/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
    imageBtnClose:			RESOURCES_PATH+'/images/lightbox/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
    imageBlank:				RESOURCES_PATH+'/images/lightbox/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
    nothing: null
};

// Ajaxifying forms
$.fn.ajaxify = function () {
	var $form = this;
	var $div = this.parents('div').eq(0);
	var submitted = false;
	$form.submit(function (e) {
		e.stopPropagation();
		e.preventDefault();
		if (submitted) return false;
		submitted = true;
		$div.stop().animate({ opacity: 0 }, { queue: false });
		$form.ajaxSubmit(function (responseText) {
			$div.text('').append(responseText);
			$div.find('> form').ajaxify();
			$div.stop().animate({ opacity: 1 }, { queue: false });
		});
		return false;
	});
}

function reliansNavigationApplicationResize(x) {
  $('#menu .flashReplacement').width(x);
}

$(function () {
	(function () {
		/** Save the innerXHTML of div#menu ul, which will be requested by the ReliansFlashNavigation application */
		var content = '<ul>'+innerXHTML($('#menu ul').get(0))+'</ul>';
		var $replacement = $('<div class="flashReplacement"></div>');
		$('#menu ul').after($replacement).remove();
        
		/** Create the SWFObject and write to div#menu, replacing the old XHTML schedule */
		var swfo = new SWFObject(RESOURCES_PATH + '/flash/ReliansFlashNavigation.swf', 'reliansFlashNavigationApplication', '100%', '28', '9', '#ffffff'); 
		swfo.addParam("wmode", "transparent"); 
		swfo.addParam("allowScriptAccess", "always"); 
        swfo.addVariable("content", content.replace(/"/g, '&quot;'));
		swfo.write($replacement.get(0)); 
		
		/** When the flash application has finished hooking to JS, initialize it. */
		var app = $('#reliansFlashNavigationApplication').get(0);
		(function waitForApp() {
		    if (app.addFlashEventListener == undefined) return setTimeout(waitForApp, 333);
		    app.addFlashEventListener('resize', 'reliansNavigationApplicationResize');
		    app.resize(); 
		})();
	})();
	
	$('div.imageGallery').each(function () {
		var $div = $(this);
		var $img = $div.find('>img').css({ border: 0 });
		var $a = $('<a href=""></a>');
		var $ul = $div.find('>ul');
		var $lightboxable = $('<div></div>');
		var targetAnchor = null;
		
		$img.before($a);
		$a.append($img);
		
		function updateSelection(newValue) {
			if (newValue) {
				$a.attr('href', $(newValue).find('a').attr('href'));
				$img.attr('src', $(newValue).find('a').attr('href').replace(/\?.+/g,'') + '?__scale=w:280,h:230,t:2');
			}
			$ul.find('li').removeClass('selected');
			$(newValue).addClass('selected');
			targetAnchor = $(newValue).find('a')[0];
		}
		
		$ul.find('li').eq(0).addClass('first');
		
		$a.click(function (e) {
			e.stopPropagation();
			e.preventDefault();
			$(targetAnchor).data('alightboxable').click();
			return false;
		});
		$ul.find('a').each(function () {
			var $alightboxable = $(this).clone();
			$lightboxable.append($alightboxable);
			$(this)
				.click(function (e) {
					e.stopPropagation();
					e.preventDefault();
					updateSelection($(this).parents('li').eq(0));
					this.blur();
					return false;
				})
				.data('alightboxable', $alightboxable)
			;
		});
		$lightboxable.find('a').lightBox(LIGHTBOX_OPTIONS);
		
		updateSelection($ul.find('li')[0]);
	});
    
    /* Select replacement */
    $('#projectSearch select, #showProjects select').each(function () {
      // Declare
        var $select = $(this);
        var $field = $('<input type="hidden" />').attr({ name: $select.attr('name'), value: $select[0].value });
        var $replacement = $('<div class="select-replacement"></div>');
        var $container = $('body');
        var $globalContainer = $('<ins class="select-replacement"></ins>');
        var $ul = $('<ul></ul>');
        
      // Initialize
        $select.before($replacement);
        $select.remove();
        $replacement.before($field).append($ul);

        $replacement.click(replacementClickHandler);
        
        $select.find('option').each(function () {
            var value = $(this).attr('value');
            if (value == null) value = $(this).text();
            $ul.append(
                $('<li></li>')
                    .text($(this).text())
                    .data('value', value)
                    .click(liClickHandler)
                    .hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); })
                    .addClass(value == $select[0].value ? 'selected' : '')
            );
        });
        markSelected($ul.find('li.selected').removeClass('selected'));
        
      // Behavior
        var isDropdownOpen = false;
        function openDropdown() {
            if (isDropdownOpen) return;
            isDropdownOpen = true;
            $container.append($globalContainer.append($ul));
            var offset = $replacement.offset();
            var offset2 = $container.offset();
            $ul
                .css({ left: offset.left - offset2.left, top: offset.top - offset2.left, width: $replacement.width(), border: '1px solid #000' })
                .addClass('open')
            ;
            setTimeout(function () { $ul.find('li').removeClass('hover'); }, 33); // Another fix for IE7's rendering in-capabilities
        }
        function closeDropdown() {
            if (!isDropdownOpen) return;
            isDropdownOpen = false;
            $('html').unbind('click', closeDropdown);
            $ul
                .removeAttr('style')
                .removeClass('open')
            ;
            $replacement.append($ul);
            $globalContainer.remove();
        }
        function markSelected($li) {
            $ul.find('li')
                .css({ top: 0 })
                .css({ top: $ul.offset().top - $li.offset().top })
            ;
        }
        
        function liClickHandler(event) {
            if (!isDropdownOpen) return true;
            event.stopPropagation();
            closeDropdown();
            $field[0].value = $(this).data('value');
            var $li = $(this);
            setTimeout(function () { markSelected($li); }, 33); // Delayed this function so that IE7 can have time to calculate stuff
            return false;
        }
        
        function replacementClickHandler(event) {
            event.stopPropagation();
            openDropdown();
            $('html')
                .click()
                .one('click', closeDropdown)
            ;
            return false;
        }
    });
    
    /* Search box */
    $('#search input[type=text]')
        .focus(function () { this.value = ''; })
        .blur(function () { this.value = 'caută'; })
    ;
    
    /* Sidebar select */
    $('#sidebarRight').each(function () {
        var $divs = $('div[title]');
        var $select = $('<select></select>');
        $divs
            .each(function () {
                $select.append($('<option></option>').text($(this).attr('title')));
            })
        ;
        $select.change(function () {
            $divs.hide();
            $divs.eq(this.selectedIndex).show();
        });
        $divs.eq(0).before($('<div></div>').append($select).attr('id', 'showOffice'));

        $select[0].selectedIndex = 0;
        $select.change();
    });
	
	/* Lightbox */
	$('a.lightBox').lightBox(LIGHTBOX_OPTIONS);
	
	/* Ajaxified */
	$('form.ajaxified').ajaxify();
});

