$(document).ready(function () {
    $('.noShow').hide();
    $('.content .imageViewer li').hide();

    $('.search input[type=text]').focus(function () {
        $(this).removeClass('placeHolder');
    });
    $('.search input[type=text]').blur(function () {
        $(this).addClass('placeHolder');
    });
    if (!Modernizr.input.placeholder) {
        $(".placeHolder").each(
			function () {
			    if ($(this).val() == "" && $(this).attr("placeholder") != "") {
			        $(this).val($(this).attr("placeholder"));
			        $(this).focus(function () {
			            if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
			        });
			        $(this).blur(function () {
			            if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
			        });
			    }
			});
    }

    $('.row').each(function () {
        $(this).find('.module:first').addClass('first');
        $(this).find('.module:last').addClass('last');
    });
    $('.focus .module .body').each(function () {
        $(this).find('li:last').addClass('last');
    });
    $('.clickable').each(function (i) {
        var hrefEle = $(this).find('a').attr('href');
        $(this).click(function () {
            location.href = hrefEle;
        });
        $(this).css("cursor", "pointer");
        $(this).hover(function () {
            $(this).toggleClass('hover');
        });
    });

    equalHeight('.subNav', 'a');
    equalHeight('.focus', '.equalHeight .body');

    $(window).resize(function () {
        equalHeight('.subNav', 'a');
        equalHeight('.focus', '.equalHeight .body');
    });

    $('.copyright p:last, .path li:last').addClass('last');
    $('.quote .body').each(function () {
        /*var countParagraph = $(this).find('p').length;
        if (countParagraph > 1) {   
        $(this).find('p:last').addClass('last');
        }*/
        $(this).find('p:last').addClass('last');
    });

    $('.content table tr').each(function () {
        $(this).find('td:first').addClass('first');
        $(this).find('td:last').addClass('last');
    });
    $('.pageNav').each(function () {
        $(this).find('li:first').addClass('first');
        $(this).find('li:last').addClass('last');
        $(this).find('li li:last').addClass('last');
    });
    $('.pageNav li li').parents('li').addClass('lastWidthChildren');
    $('.module .head .pageLinks:first, .module .letter .pageLinks:first').hide();
    $('.advancedList .body ul').each(function () {
        $(this).find('li:even').addClass('even');
    });
    $('.advancedList .body table').each(function () {
        $(this).find('tr:even').addClass('even');
    });
    $('.content table').each(function () {
        $(this).find('tr:even').addClass('even');
    });
    $('.advancedList .body li').each(function () {
        $(this).find('span:first').addClass('first');
    });
    $('.advancedList .body .clickable').each(function () {
        var countItems = $(this).find('span').length;
        if (countItems > 1) {
            $(this).find('span:first').removeClass('first');
            $(this).find('span:last').addClass('last');
        }
        else {
            $(this).find('span:last').addClass('last');
        }
    });
    $('.shadow img').each(function (i, img) {
        var imageWidth = $(img).width(),
            img = $(img);
        img.load(function () {
            img.parents('.shadow').css({ width: img.width() });
        });
        if (imageWidth !== 0) {
            $(this).parents('.shadow').css('width', imageWidth);
        }
    });
    $('.shadow table').each(function () {
        $(this).parents('.shadow').addClass('fullWidth');
    });
    $('.subNav li:nth-child(4n+4)').addClass('nthChild');
    $('.imageBrowser li:nth-child(3n+4)').addClass('nthChild');
    $('.imageBrowser li:nth-child(3n+3)').addClass('last');

    $('.focus .quote').each(function () {
        var boxHeight = $(this).height();
        $('.focus .quote:after').css('height', boxHeight);
    });
    $('.pageLinks').smoothScroll({ easing: 'swing' });
    $('.home .thumbnailPeople').siblings('.head, .body, .foot').addClass('adjust');
    $('.home .calender').find('.head, .body').addClass('adjust');
    $('.newsList').children('.head, .body, .foot').addClass('adjust');
    $('.content .thumbnailPeople').parent('.module:even').addClass('breakLeft');
    $(".library .body ul:first li a").click(function (e) {
        e.preventDefault();
        if ($(this).hasClass('first')) {
            $('.library .body li').removeClass('active');
            $(this).parent('li').addClass('active');
            $('.library .body').children('ul').siblings('div').hide();
            $('.first').show();
        }
        else if ($(this).hasClass('second')) {
            $('.library .body li').removeClass('active');
            $(this).parent('li').addClass('active');
            $('.library .body').children('ul').siblings('div').hide();
            $('.second').show();
            $('.library .body .second input#databaseSearch').autocomplete({
                source: function (request, response) {
                    getResponse($('.library .body .second input#databaseSearch').val(), '/Business/CustomWebServices/LibraryDatabaseSearch.asmx/PerformDatabaseSearch', response, $('.library .body .first input#searchLanguage').val());
                },
                minLength: 2,
                delay: 125,
				position: { 
					my: "left top",
					at: "left bottom",
					offset: "1 -3",				
					of: "#databaseSearch"
				},
                select: function (event, ui) {
                    document.location.href = ui.item.value;
                    return false;
                },
                focus: function (event, ui) {
                    $('.library .body .second input#databaseSearch').val(ui.item.label);
                    return false;
                }
            });

            $('.library .body .second input#databaseSearch').bind("keydown", function (event) {
                if (event.keyCode == 13 && $('.library .body .second input#databaseSearch').data("catcomplete").menu.active) {
                    event.preventDefault();
                }
            });
        }
        else if ($(this).hasClass('third')) {
            $('.library .body li').removeClass('active');
            $(this).parent('li').addClass('active');
            $('.library .body').children('ul').siblings('div').hide();
            $('.third').show();
        }
    });
    $(".content .imageViewer ul li:first").show();
    $('.testimonial .body').each(function () {
        $(this).find('p:first').addClass('first');
    });
    $('.imageViewer .prev').click(function (e) {
        e.preventDefault();
        $(this).parents('li').hide().prev('li').show();
    });
    $('.imageViewer .prev').hover(function () {
        $(this).addClass('hoverPrev');
    }, function () {
        $(this).removeClass('hoverPrev');
    });
    $('.imageViewer .next').hover(function () {
        $(this).addClass('hoverNext');
    }, function () {
        $(this).removeClass('hoverNext');
    });
    $('.imageViewer .next, .imageViewer .nextImage a').click(function (e) {
        e.preventDefault();
        $(this).parents('li').hide().next('li').show();
    });
    $('.imageViewer .prev:first').hide();
    $('.imageViewer .next:last').hide();
    $('.imageViewer .nextImage:last a').hide();
    $('.zoom').toggle(function (e) {
        e.preventDefault();
        var src = $(this).attr("src").match(/[^\.]+/) + "-high.jpg";
        $(this).attr("src", src);
    }, function (e) {
        e.preventDefault();
        var src = $(this).attr("src").replace("-high", "");
        $(this).attr("src", src);
    });
    $(".comments ul > li").not(".comments ul li ul li").addClass('oneComment');
    $('input[type=checkbox], input[type=radio]').next('label').addClass('checkLabel');
    $('.searchResult .foot').each(function () {
        $(this).find('a:first').addClass('first');
    });
    $('.helpAndSearch .search input[type="text"]').focus(function () {
        var width = $(window).width();
        if (width > 766) {
            $(this).parents('.module').animate({ width: 250 }, 'slow');
            $(this).animate({ width: 198 }, 'slow');
        }
    });
    $('.helpAndSearch .search input[type="text"]').blur(function () {
        var width = $(window).width();
        if (width > 766) {
            $(this).animate({ width: 126 }, 'slow');
            $(this).parents('.module').animate({ width: 170 }, 'slow');
        }
    });

    $('.buy .body li').each(function () {
        var countSpans = $(this).find('span').length;
        if (countSpans > 1) {
            $(this).find('span:last').addClass('last');
        }
    });
    $('.focus .sub2Nav .body li:nth-child(n+5)').addClass('break');
    $('.buy .body').siblings('.foot').addClass('arrow');
    $('.PagingContainer a:last').addClass('last');

    //Library Search execution (BIBSYS)
    $('.library .body .first input.librarySearch:image').click(function () {
        var options = 'location=1,status=1,scrollbars=1,resizable=1,toolbar=1,menubar=1,directories=1,width=820,height=600,screenX=10,screenY=10,left=10,top=10';
        var query2 = encodeURIComponent($('#bibsysSearch').val());
        var lang = $('#searchLanguage').val();
        var target = "http://ask.bibsys.no/ask/action/result?cmd=&kilde=biblio%3ABI&q=" + query2 + "&treffPrSide=50&lang=" + lang;
        var radioSearchStudentPapers = $('.library #studentoppgaver');
        var radioSearchMagazines = $('.library #etidsskrifter');
        if (radioSearchStudentPapers.is(':checked')) {
            target = "http://ask.bibsys.no/ask/action/result?cmd=&kilde=biblio&fid=avdelingsamling&term=bi%3F&op=and&fid=bd&bibliografi=&materiale=hovedfagsoppg&materiale=studentoppg&arstall=&sortering=sortdate-&treffPrSide=50&term=" + query2 + "&lang=" + lang;
        } else if (radioSearchMagazines.is(':checked')) {
            var target = "http://ask.bibsys.no/ask/action/result?cmd=&kilde=biblio%3ABI&fid=tittel-ord&term=" + query2 + "&op=and&fid=bd&term=&bibliografi=&materiale=tidsskrift.e&avdeling=&arstall=&sortering=sorttitle&treffPrSide=50&lang" + lang;
        }

        window.open(target, "Bibliotekssok", options, false);
        return false;
    });

    //Library Search execution (DATABASE)
    $('.library .body .second input.librarySearch:image').click(function () {
        var options = 'location=1,status=1,scrollbars=1,resizable=1,toolbar=1,menubar=1,directories=1,width=820,height=600,screenX=10,screenY=10,left=10,top=10';
        var query2 = encodeURIComponent($('#googleScholar').val());
        var lang = $('#searchLanguage').val();
        var target = "http://scholar.google.no/scholar?q=" + query2 + "&hl=" + lang + "&btnG=S%C3%B8k";

        window.open(target, "Bibliotekssok", options, false);
        return false;
    });

    //Library Search execution (GOOGLE SCHOLAR)
    $('.library .body .third input.librarySearch:image').click(function () {
        var options = 'location=1,status=1,scrollbars=1,resizable=1,toolbar=1,menubar=1,directories=1,width=820,height=600,screenX=10,screenY=10,left=10,top=10';
        var query2 = encodeURIComponent($('#googleScholar').val());
        var lang = $('#searchLanguage').val();
        var target = "http://scholar.google.no/scholar?q=" + query2 + "&hl=" + lang + "&btnG=S%C3%B8k";

        window.open(target, "Bibliotekssok", options, false);
        return false;
    });

    if (typeof initializeGoogleMaps == 'function') {
        initializeGoogleMaps();
    }

    $('input', 'div.library').keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            if ($('.library .body .first input.librarySearch:image').is(":visible")) {
                $('.library .body .first input.librarySearch:image').click();
            } else if ($('.library .body .third input.librarySearch:image').is(":visible")) {
                $('.library .body .third input.librarySearch:image').click();
            }
            return false;
        } else {
            return true;
        }
    });
});

function getResponse(input, webMethod, response, languageBranch) {
    var data = { searchQuery: input, languageBranch: languageBranch };
    return $.ajax({
        type: "POST",
        url: webMethod,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            response($.map(JSON.parse(msg.d), function (item) {
                return {
                    label: item.PageName,
                    value: item.LinkUrl,
                    category: item.PageTypeName,
                    desc: item.Description
                };
            }));
            $(input).removeClass("ui-autocomplete-loading");
        }
    });
}

//Equal heights
function equalHeight (container, toResize) {
	$(container).each(function (i) {
		var H = 0,
			h,
			i,
			mylink,
			links = $(this).find(toResize);		
		for (i = 0; i < links.length; i++) {
			mylink = $(links[i]);
			mylink.css('height','auto');
			h = mylink.height();
			if (h > H) H = h;
		}		
		links.height(H);
	});
}


//Google maps
function getMapOptions(myLatlng, zoomlevel) {
    var mapOptions = {
        zoom: zoomlevel,
        maxZoom: 17,
        center: myLatlng,
        mapTypeControl: false,
        streetViewControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    return mapOptions;
}

function applyMarkers(point, map, info, iconImage) {
    var marker = new google.maps.Marker({
        position: point,
        map: map,
        title: info,
        icon: iconImage
    });
    
    var infoWindow = new google.maps.InfoWindow({ maxWidth: 200 });
    google.maps.event.addListener(marker, 'click', function () {
        infoWindow.setContent(info);
        infoWindow.open(map, marker);
    });
}

function setSearchBoxText(checkBoxNumb) {
    if (checkBoxNumb == 0) {
        $('.library .body .first input#bibsysSearch').val($('.library .body .first input#librarycatalogsearchboxtext').val());
    } else if (checkBoxNumb == 1) {
        $('.library .body .first input#bibsysSearch').val($('.library .body .first input#studentpaperssearchboxtext').val());
    } else {
        $('.library .body .first input#bibsysSearch').val($('.library .body .first input#emagazinessearchboxtext').val());
    }
}
