/* Author: Ifab/Drum */

/* Colobox initiation */
$(document).ready(function(){
	//Examples of how to assign the ColorBox event to elements
	$("a[rel='example1']").colorbox();
	$("a[rel='example2']").colorbox({transition:"fade"});
	$("a[rel='example3']").colorbox({transition:"none", width:"75%", height:"75%"});
	$("a[rel='example4']").colorbox({slideshow:true});
	$(".example5").colorbox({width:"600", inline:true, href:"#share"});
	$(".example6").colorbox({width:"600", inline:true, href:"#emailItem"});
	$(".example7").colorbox({width:"600", inline:true, href:"#reportItem"});
	$(".example8").colorbox({width:"600", inline:true, href:"#reportThis"});
	$(".example9").colorbox({width:"600", inline:true, href:"#poster"});
	$(".honor_link").colorbox({onOpen: function(){addTheme("honor_box");}, onClosed:function(){removeTheme("honor_box");}, width:"562", height:"565", inline:true, href:"#nominateForTribute", top:"0", left:"226"});
	
	//$(".honor_link2").colorbox({onOpen: function(){addTheme("honor_box");}, onClosed:function(){removeTheme("honor_box");}, width:"562", height:"565", inline:true, href:"#nominateForTribute", top:"0", left:"226"});
	$(".honor_link2").colorbox({onOpen: function(){addTheme("honor_box");}, iframe:true, innerWidth:562, innerHeight:565, top:"0", left:"226"});
	$("a.tribute").colorbox({onOpen: function(){addTheme("single-tribute");}, iframe:true, innerWidth:675, innerHeight:678, top:"0", left:"226"});
	$("a.search").colorbox({onOpen: function(){addTheme("chrono-search");}, iframe:true, innerWidth:675, innerHeight:678, top:"0", left:"226"});
	$(".report_this").colorbox({onOpen: function(){addTheme("report_this");}, onClosed:function(){removeTheme("report_this");}, width:"500", height:"320", inline:true, href:"#reportThis"});
	$(".report_this_tribute").colorbox({onOpen: function(){addTheme("report_this_tribute");}, onClosed:function(){removeTheme("report_this_tribute");}, width:"500", height:"320", inline:true, href:"#reportThisForm"});
	$(".share_this").colorbox({onOpen: function(){addTheme("share_this");}, onClosed:function(){removeTheme("share_this");}, width:"675", height:"678", inline:true, href:"#shareThis", top:"0", left:"0"});
	$("a.email").colorbox({onOpen: function(){addTheme("email");}, onClosed:function(){removeTheme("email");}, width:"675", height:"678", inline:true, href:"#shareThisEmail", top:"0", left:"0"});
    //Example of preserving a JavaScript event for inline calls.
	$("#click").click(function(){ 
		$('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
		return false;
	});
});

/*...colorbox({
   onOpen: function(){addTheme("theme2");},
   onClosed:function(){removeTheme("theme2");}
});*/
function addTheme(id){
    $("#cboxOverlay, #colorbox").addClass(id);
}
function removeTheme(id){
    $ ("#cboxOverlay, #colorbox").removeClass(id);
}

/* Funktion som skriver ut en tumnagel på startsidan */
function TributeThumbnailWriter(name, url, img, org, txt) {
              
    var printThis = '\
        <li class="">\
            <a href="' + url + '" class="tribute">\
                <img src="' + img + '" alt="name-of-person" />\
                <div class="feat_info">\
					<hgroup><h1>' + name + '</h1><h2>' +org + '</h2></hgroup>\
					<blockquote cite="person-who-said-this">\
						<p>”' + txt + '”</p>\
					</blockquote>\
				</div>\
			</a>\
		</li>\
    ';

    return printThis;
}

function TributeThumbnailWriterHidden(url) {
    var printThis = '<li class="hidden" script="display:none;"><a href="' + url + '" class="tributehidden" onclick="colorbox({onOpen: function(){addTheme(\"single-tribute\");}, iframe:true, innerWidth:675, innerHeight:678, top:\"0\", left:\"226\"});"></a></li>';
    return printThis;
}

/* Toggle labels */
(function($) {
    function toggleLabel() {
        var input = $(this);
        setTimeout(function() {
            var def = input.attr('title');
            if (!input.val() || (input.val() == def)) {
                input.prev('span').css('visibility', '');
                if (def) {
                    var dummy = $('<label></label>').text(def).css('visibility','hidden').appendTo('body');
                    input.prev('span').css('margin-left', dummy.width() + 3 + 'px');
                    dummy.remove();
                }
            } else {
                input.prev('span').css('visibility', 'hidden');
            }
        }, 0);
    };

    function resetField() {
        var def = $(this).attr('title');
        if (!$(this).val() || ($(this).val() == def)) {
            $(this).val(def);
            $(this).prev('span').css('visibility', '');
        }
    };

    $('input, textarea').live('keydown', toggleLabel);
    $('input, textarea').live('paste', toggleLabel);
    $('select').live('change', toggleLabel);

    $('input, textarea').live('focusin', function() {
        $(this).prev('span').css('color', '#87b3e2');
    });
    $('input, textarea').live('focusout', function() {
        $(this).prev('span').css('color', '#FFF');
    });

    $(function() {
        $('input, textarea').each(function() { toggleLabel.call(this); });
    });

})(jQuery);


/*
 * Style File - jQuery plugin for styling file input elements
 * Copyright (c) 2007-2008 Mika Tuupola
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 * Based on work by Shaun Inman
 *   http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
 * Revision: $Id: jquery.filestyle.js 303 2008-01-30 13:53:24Z tuupola $
 */

(function($) {
    
    $.fn.filestyle = function(options) {
                
        /* TODO: This should not override CSS. */
        var settings = {
            width : 182
        };
                
        if(options) {
            $.extend(settings, options);
        };
                        
        return this.each(function() {
            
            var self = this;
            var wrapper = $("<div class='file_wrapper'>")
                            .css({
                                //"width": settings.imagewidth + "px",
                                //"height": settings.imageheight + "px",
                                //"background": "url(" + settings.image + ") 0 0 no-repeat",
                                //"background-position": "right",
                                //"display": "inline",
                                //"position": "absolute",
                                //"overflow": "hidden"
                            });
                            
            var filename = $('<input class="file">')
                             .addClass($(self).attr("class"))
                             .css({
                                 "display": "inline",
                                 "width": settings.width + "px"
                             });

            $(self).before(filename);
            $(self).wrap(wrapper);

            $(self).css({
                        "position": "relative",
                        //"height": settings.imageheight + "px",
                        "width": settings.width + "px",
                        //"display": "inline",
                        "cursor": "pointer"
                        //"opacity": "0.0"
                    });

            $(self).bind("change", function() {
                filename.val($(self).val());
            });
      
        });
        

    };
    
})(jQuery);

  $(function() {          
      $("input.file_1").filestyle({ 
          //image: "img/ladda_upp_en_bild.png",
          //imageheight : 35,
          //imagewidth : 82,
          width : 182
      });
	});
	
/* checkboxes */
$(function(){
	$('input.accept_1').checkBox();
});

function closeIframe(){
    parent.$.fn.colorbox.close();
}
function closeInframe(){
    $.fn.colorbox.close();
}

function OpenTribute(myParam) {
   //if (typeof myParam != "undefined") {      
   if (typeof myParam == "string") {    
       if(myParam != ""){
            var url = "/templates/Pages/Tribute/ViewTribute.aspx?tributeId=" + myParam;           
            $.colorbox({ onOpen: function () { addTheme('single-tribute'); }, onClosed:function(){removeTheme("single-tribute");}, iframe: true, innerWidth: 675, innerHeight: 678, top: '0', left: '226', href:url});
       }
    }
}

function OpenPopup(myParam) {
    if (typeof myParam == "string") {
        if (myParam != "") {
            var url = myParam;
            $.colorbox({ onOpen: function () { addTheme('single-tribute'); }, onClosed: function () { removeTheme("single-tribute"); }, iframe: true, innerWidth: 675, innerHeight: 678, top: '0', left: '226', href: url });
        }
    }
}

function getQueryString() {
    var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
    while (m = re.exec(queryString)) {
        result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
    return result;
}

function getTributeId()
{
    var url = location.toString();
    var id = url.substr(url.toString().indexOf("#") + 1 ,url.length);

    if( id.indexOf("http") == 0 ){
        return null;
    } else {
        return id;
    }
}

function startThumbnails(type) {

    if (type == "start") {
        $('#linkMap').append('<li class="spacer"></li>');
        $("#linkMap").width(startWidth + 113);   
        var avHeight = (parseInt(startHeight / 113, 10) + 1);
        var avWidth = Math.floor((startWidth+113)/ 113);
        var newNoOfThumbnails = ((avHeight * avWidth) - 4);
        noOfThumbnails = newNoOfThumbnails;
        getTribute(newNoOfThumbnails);
    }
    else {        
        var avHeight = (parseInt($(window).height() / 113, 10) + 1);
        var avWidth = Math.floor(($(window).width()+113) / 113);
        $("#linkMap").width($(window).width() + 113);   
        var newNoOfThumbnails = ((avHeight * avWidth) - 4);

        /* Beräkna fram hur många nya tumngalar som skall visas */
        var addNoOfThumbnails = newNoOfThumbnails - noOfThumbnails;

        if (addNoOfThumbnails > 0) {
            noOfThumbnails = newNoOfThumbnails;
            printer(TributeList, addNoOfThumbnails);
        }
    }
}

/* Funktionen som hämtar upp rätt antal hyllningar att visa på startsidan */
function getTribute(no) {
    $.ajax({
        type: "POST",
        url: "/templates/Pages/Tribute/TributeWebService.asmx/GetTributes",
        data: "{'no' : " + no + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {

            $.each(data.d, function () {
                var tp = new TributePost(this.Name, this.URL, this.ImageURL, this.Organisation, this.Text);
                TributeList.push(tp);
            });

            printer(TributeList, no);
        },
        error: function () {
            var tp = new TributePost("Ledsen men...", "/templates/Pages/Tribute/ViewTribute.aspx?tributeId=0", "/images/Tribute/sorry_but.jpg", "nu blev det knas...", "Något gick helteokigt med hämtningen från databasen... sorry :(");
            TributeList.push(tp);

            printer(TributeList, no);
        }
    });

}

function TributePost(name, url, imageurl, organisation, text) {
    this.Name = name;
    this.URL = url;
    this.ImageURL = imageurl;
    this.Organisation = organisation;
    this.Text = text;
}

/* Funktion för att skriva ut... */
function printer(TributeList, NoOfThumbnailsToAdd) {

    var TribList = new Array();

    if (NoOfThumbnailsToAdd > 0) {

        if (TributeList.length > NoOfThumbnailsToAdd) {
            // CUT
            TribList = TributeList.slice(0, NoOfThumbnailsToAdd);
        } else {
            // ADD
            TribList = repeate(TributeList, NoOfThumbnailsToAdd);
        }
                
        $.each(TribList, function () {
            $('#linkMap .spacer').after(TributeThumbnailWriter(this.Name, this.URL, this.ImageURL, this.Organisation, this.Text));
        });

        $("a.tribute").colorbox({ onOpen: function () { addTheme("single-tribute"); }, iframe: true, innerWidth: 675, innerHeight: 678, top: "0", left: "226" });
        //$(document).ready(function () {
        var v = $("#linkMap > li").css('visibility', 'hidden'), cur = 0;
        for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
        function fadeInNextLI() {
            v.eq(cur++).css('visibility', 'visible').hide().fadeIn('fast');
            if (cur != v.length) setTimeout(fadeInNextLI, 5);
        }
        fadeInNextLI();
        //});        
    }            
}

/* Funktion för att fylla ut en array */
function repeate(arr, count) {
    var ln = arr.length;
    var b = new Array();
    for (i = 0; i < count; i++) {
        b.push(arr[i % ln]);
    }
    return b;
}

$(document).ready(function () {
    $('#linkMap li').hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });
});

