jQuery(document).ready(function() {
    Cordaan.Compare.Init();
    Cordaan.Compare.Menu.UpdateMenu(); 
    Cordaan.Compare.Menu.Init();
    Cordaan.Compare.ResizeColumns();
});

if(typeof(Cordaan) == 'undefined') {
	Cordaan = function() {}
}

Cordaan.Compare = function() {}

Cordaan.Compare.Init = function() {
    if ($("#RemoveInPage") != null && $("#RemoveInPage").val() == 'true') {
        // We are on the comparator page
        $('.locationOverview ul.list li div a.remove').click(Cordaan.Compare.HideColumns);
    } else {
        // We are on the overview or a detail page
        // Bind add event
        $('.locationOverview .listWrapper ul li div a:not(.remove)').click(Cordaan.Compare.Add);

        // Bind remove event
        $('.locationOverview .listWrapper ul li div a.remove').click(Cordaan.Compare.Remove);
    }
}

Cordaan.Compare.ResizeColumns = function() {
  if ($("#RemoveInPage") != null && $("#RemoveInPage").val() == 'true') {
      // We are on the comparator page
    if (jQuery.browser.msie && jQuery.browser.version.charAt('0') <= '7') {
        $('col:first').attr('width', 315);
    }
    if (jQuery.browser.safari) {
      var emptyCols = ( 4 - Cordaan.Compare.NumSelected() );
      var lastEmptyCol = emptyCols + 2;
      var firstcolwidth = parseInt($('col:first').attr('width')) + ( emptyCols * 143 );
      $('col:first').attr('width', firstcolwidth);
      for (var x = 2; x < lastEmptyCol; x++)
      {
        $('col:nth-child(' + x + ')').attr('width', 0);
      }
    }
  }
}

Cordaan.Compare.Add = function() {
	// Check if full
	if(Cordaan.Compare.NumSelected() == 4) {
		Cordaan.Compare.Full();
		return;
	}

	// Get the li element and id where the link is positioned
	var contentLi = $(this).parent().parent();
	var id = contentLi.attr('id');

	// Change the 'Vergelijk' link into 'Verwijder'
	var contentLink = $('div a', contentLi);
	contentLink.text('Verwijder');
	contentLink.attr('title', 'Verwijder')
	contentLink.addClass('remove');
	contentLink.unbind('click');

	// Get the compare menu li element where the selected element should be placed
	var menuUl = $('.compareSelection .layerWrapper ul');
	var menuLi = $('li.empty:first', menuUl);

	// Clean the compare menu element and copy the contentLi
	menuLi.empty().removeClass('empty');
	menuLi.html(contentLi.html());

	// Remove the text paragraph from the menu element
	$('p', menuLi).remove();

	// Append a hidden input field with the seleted id value
	var idInput = jQuery('<input type="hidden" name="compareSelection" />');
	idInput.attr('value', id);
	menuLi.append(idInput);

	// Attach the correct click event to the content link and the menu link
	contentLink.click(Cordaan.Compare.Remove);
	$('a.remove', menuLi).click(Cordaan.Compare.Menu.Remove);

	// Set the correct number of selected elements in the compare menu heading
	Cordaan.Compare.Menu.UpdateTitle(menuUl);

	Cordaan.Compare.Menu.UpdateCookie(menuUl);
}

Cordaan.Compare.Remove = function() {
	// Get the li element and id where the link is positioned
	var contentLi = $(this).parent().parent();
	var id = contentLi.attr('id');

	// Get the corresponding compare menu li
	var menuLi = $('.compareSelection input[value=' + id + ']').parent();

	// Do the actual remove action
	Cordaan.Compare.DoRemove(contentLi, menuLi);
}

Cordaan.Compare.DoRemove = function(contentLi, menuLi) {
	// Get the menu element parent
	menuUl = menuLi.parent();

	// Remove the menu element
	menuLi.remove();

	// Reditribute the 'odd' class
	$('li:odd', menuUl).removeClass('odd');
	$('li:even', menuUl).each(function() {
		if(!$(this).hasClass('odd')) {
			$(this).addClass('odd');
		}
	});

	// Create an empty li element for in the menu
	var emptyMenuLi = jQuery('<li/>');
	emptyMenuLi.attr('class', 'empty');
	emptyMenuLi.unbind("click");
	emptyMenuLi.click(Cordaan.Compare.Menu.GoToBrowser);

	menuUl.append(emptyMenuLi);

	// Change the 'Verwijder' content link into 'Vergelijk'
	var contentLink = $('div a', contentLi);
	contentLink.text('Vergelijk');
	contentLink.attr('title', 'Vergelijk')
	contentLink.removeClass('remove');
	contentLink.unbind('click');
	contentLink.click(Cordaan.Compare.Add);

	// Set the correct number of selected elements in the compare menu heading
	Cordaan.Compare.Menu.UpdateTitle(menuUl);

	Cordaan.Compare.Menu.UpdateCookie(menuUl);
}

Cordaan.Compare.NumSelected = function(menuUl) {
	if(menuUl == null) {
		menuUl = $('.compareSelection .layerWrapper ul');
	}
	return $('li:not(.empty)', menuUl).length;
}

Cordaan.Compare.Full = function() {
    Cordaan.Compare.ShowMessage('Uw kunt maximaal 4 locaties vergelijken.');
}

Cordaan.Compare.ShowMessage = function(message) {
    // Show content mask
    $('.columnContent .mask').show();
    var layer = $('#compareMenuFull');
    var container = layer.parent();
    var button = $('a.button', layer);
    var textarea = $('p', layer);
    textarea.text(message);
    layer.css('left', (container.width() - layer.width()) / 2);
    layer.css('top', (container.height() - layer.height()) / 2);

    button.click(function() {
        $(this).parent().hide();
        $('.columnContent .mask').hide();
    });

    layer.show();

    button.css('margin-left', (layer.width() - button.width()) / 2);
}

Cordaan.Compare.Menu = function() { }

Cordaan.Compare.Menu.Init = function() {
    // Bind menu open event
    $('.compareSelection > a').click(Cordaan.Compare.Menu.Open);

    // Bind remove event
    $('.compareSelection .layerWrapper .inner ul li div a').unbind("click");
    if ($("#RemoveInPage") != null && $("#RemoveInPage").val() == 'true') {
        // We are on the comparator page
        $('.compareSelection .layerWrapper .inner ul li div a').click(Cordaan.Compare.Menu.HideColumns);
    } else {
        $('.compareSelection .layerWrapper .inner ul li div a').click(Cordaan.Compare.Menu.Remove);
    }

    $('.compareSelection .layerWrapper .inner .button a').click(Cordaan.Compare.Menu.Compare);
    $('.compareSelection .layerWrapper ul li.empty').unbind("click");
    $('.compareSelection .layerWrapper ul li.empty').click(Cordaan.Compare.Menu.GoToBrowser);
}

Cordaan.Compare.Menu.Open = function() {
    // Show content mask
    $('.columnContent .mask').show();

    // Show layer
    $('.compareSelection .layerWrapper').show();

    // Add active class to button
    $(this).addClass('active');

    // Rebind click event to close function
    $(this).unbind('click');
    $(this).click(Cordaan.Compare.Menu.Close);

    $(document).click(Cordaan.Compare.Menu.CloseMenu);
    $('.compareSelection').click(function(e) {
        e.stopPropagation();
    });

}

Cordaan.Compare.Menu.CloseMenu = function() {
    $('.compareSelection a').triggerHandler("click")
}


Cordaan.Compare.Menu.Close = function() {
    // Hide content mask
    $('.columnContent .mask').hide();

    // Hide layer
    $('.compareSelection .layerWrapper').hide();

    // Remove active class to button
    $(this).removeClass('active');

    // Rebind click event to open function
    $(this).unbind('click');
    $(this).click(Cordaan.Compare.Menu.Open);

    $(document).unbind('click');

}

Cordaan.Compare.Menu.Remove = function() {
	// Get the compare menu li element and id
	var menuLi = $(this).parent().parent();
	var id = $('input', menuLi).attr('value');

	// Get the corresponding content li
	var contentLi = $('.locationOverview li#' + id);

	// Do the action remove action
	Cordaan.Compare.DoRemove(contentLi, menuLi);
}

Cordaan.Compare.Menu.RemoveAll = function() {
    // Loop through all not empty li elements of the compareselection ul
    $('.compareSelection .layerWrapper ul li:not(.empty)').each(function() {
        // Get the compare menu li element and id
        var menuLi = $(this);
        var id = $('input', menuLi).attr('value');

        // Get the corresponding content li
        var contentLi = $('.locationOverview li#' + id);

        // Do the action remove action
        Cordaan.Compare.DoRemove(contentLi, menuLi);
    });
}


Cordaan.Compare.Menu.UpdateTitle = function(menuUl) {
	if(menuUl == null) {
		menuUl = $('.compareSelection .layerWrapper ul');
	}
	var title = 'Vergelijk (' + Cordaan.Compare.NumSelected(menuUl) + '/4)';

	$('.locationFinderTitle .compareSelection > a > span').text(title);
}

Cordaan.Compare.Menu.UpdateCookie = function(menuUl) {
    if (menuUl == null) {
        menuUl = $('.compareSelection .layerWrapper ul');
    }
    var ComparisonIds = "";
    var ComparisonIdSeparator = "";
    $('input', menuUl).each(function() {
        ComparisonIds += ComparisonIdSeparator + $(this).val();
        ComparisonIdSeparator = ",";
        var menuLi=$(this).parent();
        var link = $('a', menuLi).attr('href');
        var img = $('img', menuLi).attr('src');
        var title = $('strong', menuLi).text();
        jQuery.cookie('ComparisonIds.' + $(this).val() + ".url", link ,{ path: '/'});
        jQuery.cookie('ComparisonIds.' + $(this).val() + ".img", img ,{ path: '/'});
        jQuery.cookie('ComparisonIds.' + $(this).val() + ".title", title  ,{ path: '/'});
    });
    if (ComparisonIds.length > 0) {
        jQuery.cookie('ComparisonIds', ComparisonIds ,{ path: '/'});
    } else {
        jQuery.cookie('ComparisonIds', null, { path: '/' });
    }
}

Cordaan.Compare.Menu.UpdateMenu = function(menuUl) {
    if (menuUl == null) {
        menuUl = $('.compareSelection .layerWrapper ul');
    }
    var ComparisonIdString = jQuery.cookie('ComparisonIds');
    var ComparisonIds = [];
    if (ComparisonIdString == null) {
        return;
    }

    ComparisonIds = ComparisonIdString.split(',');
    $(ComparisonIds).each(function() {
        var menuLi = $('li.empty:first', menuUl);
        var entryUrl = jQuery.cookie('ComparisonIds.' + this + ".url");
        var entryImg = jQuery.cookie('ComparisonIds.' + this + ".img");
        var entryTitle = jQuery.cookie('ComparisonIds.' + this + ".title");
        // Clean the compare menu element and copy the contentLi
        menuLi.unbind("click");
        menuLi.empty().removeClass('empty');

        var menuLiHtml = '<a href="' + entryUrl + '"><img style="border-width: 0px;" src="' + entryImg + '"></a>' +
                '<br/><strong><div>' + entryTitle + '</div></strong>' +
                '<div><a class="remove" href="javascript:;" title="Verwijder">Verwijder</a></div>';


        menuLi.html(menuLiHtml);

        // Remove the text paragraph from the menu element
        $('p', menuLi).remove();

        // Append a hidden input field with the seleted id value
        var idInput = jQuery('<input type="hidden" name="compareSelection" />');
        idInput.attr('value', this);
        menuLi.append(idInput);

        $('a', menuLi).unbind("click");
        if ($("#RemoveInPage") != null && $("#RemoveInPage").val() == 'true') {
            // We are on the comparator page
            $('a.remove', menuLi).click(Cordaan.Compare.Menu.HideColumns);
        } else {
            $('a.remove', menuLi).click(Cordaan.Compare.Menu.Remove);
        }
    });

    Cordaan.Compare.Menu.UpdateTitle(menuUl);

}

Cordaan.Compare.Menu.Compare = function() {
    if (Cordaan.Compare.NumSelected() > 1) {
        window.location = $("#comparatorurl").val();
        return true;
    } else {
        Cordaan.Compare.ShowMessage('Kies minimaal 2 locaties om te vergelijken.');
    }
}

Cordaan.Compare.Menu.GoToBrowser = function() {
    window.location = $("#locationBrowserUrl").val();
    return true;
}

Cordaan.Compare.ShowHide = function(checkButton) {
    var tab = $(checkButton).closest("div");
    if ($(checkButton).attr("checked")) {
        $('tr.equal', tab).each(function() { $(this).hide() });
        $('table', tab).each(function() {
            if ($('tbody tr:visible', this).length == 0) {
                $(this).hide();
            }
        });
    } else {
        $('table', tab).each(function() { $(this).show() });
        $('tr.equal', tab).each(function() { $(this).show() });
    }
    $('table', tab).each(function() {
        var evenRow = false;
        $('tr:visible', this).each(function() { 
            if(evenRow){
                if (!$(this).hasClass('even')) {
                    $(this).addClass('even');
                }
            } else {
                $(this).removeClass('even');
            }
            evenRow=!evenRow;
        });
    });
}

Cordaan.Compare.HideColumns = function() {
    if (Cordaan.Compare.NumSelected() <= 2) {
        Cordaan.Compare.ShowMessage('Er moeten minimaal 2 locaties zijn om te vergelijken.');
        return;
    }
    var contentLi = $(this).closest("li");
    var id = contentLi.attr('id');
    var menuLi = $('.compareSelection input[value=' + id + ']').parent();

    Cordaan.Compare.DoHideColumns(contentLi, menuLi);
}

Cordaan.Compare.Menu.HideColumns = function() {
    if (Cordaan.Compare.NumSelected() <= 2) {
        Cordaan.Compare.ShowMessage('Er moeten minimaal 2 locaties zijn om te vergelijken.');
        return;
    }
    var menuLi = $(this).closest("li");
    var id = $('input', menuLi).attr('value');
    var contentLi = $('.locationOverview li#' + id);

    Cordaan.Compare.DoHideColumns(contentLi, menuLi);
}

Cordaan.Compare.DoHideColumns = function(contentLi, menuLi) {
    Cordaan.Compare.DoRemove(contentLi, menuLi);
    var index = $('.locationOverview  ul.list li').index(contentLi);
    index += 2;
    $(contentLi).hide();
    $('td:nth-child(' + index + ')').hide();

    $('th').each(function() {
        var curspan = parseInt($(this).attr('colspan')) + 1;
        $(this).attr('colspan', curspan)
    });

    // Only for ie6 and ie7
    if (jQuery.browser.msie && jQuery.browser.version.charAt('0') <= '7') {
        var firstcoldef = $('col:first');
        var firstcolwidth = parseInt($('col:first').attr('width')) + 143;
        $('col:first').attr('width', firstcolwidth);
    }
    $('div.tabContent table').each(function() {
        var tab = $(this).closest("div");
        var hideEqual = false;
        var hideTable = true;
        var evenRow = false;
        var checkButton = $('input', tab);
        if ($(checkButton).attr("checked")) {
            hideEqual = true;
        }
        $('tr', this).each(function() {
            var equalRow = true;
            var rowValue = null;
            $('td', this).each(function() {
                if ($(this).css("display") != "none") {
                    if (rowValue == null) {
                        rowValue = $(this).text();
                    }
                    if (rowValue != $(this).text()) {
                        equalRow = false;
                    }
                }
            });
            if (equalRow) {
                $(this).addClass('equal');
                if (hideEqual) {
                    $(this).hide();
                }
            } else {
                hideTable = false;
            }
            if (!hideEqual || !equalRow){
                if (evenRow) {
                    if (!$(this).hasClass('even')) {
                        $(this).addClass('even');
                    }
                } else {
                    $(this).removeClass('even');
                }
                  evenRow = !evenRow;
            }
        });
        if (hideEqual && hideTable) {
            $(this).hide();
        }
    });
}
