/* voor CDMM Javascripts */



/* Vermijden dat console functie van Firebug errors veroorzaakt bij mensen/browsers die geen Firebug hebben. */
if (typeof (console) === "undefined" || typeof (console.log) === "undefined") var console = { log: function() { } };


/*********************************************************************************************************
* Breaking News slide show (versie 2)
*
* @author		Roger Hamelers
*/

$(function () {

	/* Move slides out of the screen real estate. */
	//$('.slideBox .slide').css('display', 'block').css('margin', '-3000px');
	//TEMPhelliptisize('.slide');
	//$('.slideBox .slide').css('margin', '0px');

		$('.thumbs a:first').addClass('selected');
		var options = {
			slideChange: function (currentIndex) {
				$('.thumbs a').removeClass('selected');
				$('.thumbs a:eq(' + currentIndex + ')').addClass('selected');
			},
			slideType: 'fade',
			fadeIntOut: true,
			showTime: 6000,
			doHoverPause: false
		};
		$('.slideBox .slide').dumbCrossFade(options);
		var i = 0;
		$('.thumbs a').each(function () {
			$(this).attr('href', i + '');
			i++;
		});
		$('.thumbs a').click(function () {
			$('.slideBox .slide')
					.dumbCrossFade('jump', parseInt($(this).attr('href')));
			return false;
		});
	
});



/* Run this stuff when DOM has loaded */
$(function() {



    /** 
    * Display y-position of XL-leaderboard 
    */

    /*var position = $("#xl-leaderboard").position();
    console.log('########## LEADERBOARD ##########');
    console.log("Leaderboard staat op " + position.top + "px van boven.");
    alert("Leaderboard staat op " + position.top + "px van boven.");*/

    BindPullDownMenu();


    /*********************************************************************************************************
    * Set hover effect on search button. 
    */
    $('#zoek .button').mouseover(function() {
        $(this).removeClass('button');
        $(this).addClass('btnHover');
    })
    $('#zoek .button').mouseout(function() {
        $(this).removeClass('btnHover');
        $(this).addClass('button');
    })

    /*********************************************************************************************************
    * Set hover effect on 'Recepten' en 'Albums'.
    * Basically a work around for IE's lack of hover on li elements. 
    */
    $('.infiniteCarousel li a').mouseover(function() {
        $(this).css('background-color', '#cc0000').css('color', '#ffffff');
        $(this).parent().css('background-color', '#cc0000').css('color', '#ffffff');
    });
    $('.infiniteCarousel li a').mouseout(function() {
        $(this).css('background-color', '#000000').css('color', '#ffffff');
        $(this).parent().css('background-color', '#000000').css('color', '#ffffff');
    });
    $('.receptenCarousel li a').mouseover(function() {
        $(this).css('background-color', '#cc0000').css('color', '#ffffff');
        $(this).parent().css('background-color', '#cc0000').css('color', '#ffffff');
    });
    $('.receptenCarousel li a').mouseout(function() {
        $(this).css('background-color', '#777777').css('color', '#ffffff');
        $(this).parent().css('background-color', '#777777').css('color', '#ffffff');
    });


    /*********************************************************************************************************
    * Highlight search box based on focus and blur. 
    */

    var searchBox = $('#zoek input');

    searchBox.focus(function(e) {
        $(this).addClass("active");
    });
    searchBox.blur(function(e) {
        $(this).removeClass("active");
    });

    // Set text on blur and remove text on focus. 

    searchBoxDefaultText = searchBox.attr("value");

    searchBox.focus(function() {
        if ($(this).attr("value") == searchBoxDefaultText) $(this).attr("value", "");
    });
    searchBox.blur(function() {
        if ($(this).attr("value") == "") $(this).attr("value", searchBoxDefaultText);
    });


    /*********************************************************************************************************
    * On article pages, remove empty gallery slides by replacing them with another background-image.
    */
    $('#articleGallery li').each(

			function checkForEmpty() {
			    if ($(this).is(':empty')) {
			        $(this).css('backgroundImage', 'url(http://localhost/she/assets/img/bg_slide_empty.png)');
			    } else {
			        // Do Nothing
			    }
			}
		);


    /*********************************************************************************************************
    * Set width/styling of items in #block6 - MODEL07.
    * Because the total available width is an uneven number of grid columns, the two articles leave an open gap (1 grid column).
    * The folowing code restyles the article blocks to overule the styling of the articles to fill that gap when possible.
    */

    /* Determine if images are landscape or portrait; .not(":last") necessary to prevent selecting to many children. */
    var imgCombo = "";
    var img1Format = $('#overview #block6 div:nth-child(2) span').width() < $('#overview #block6 div:nth-child(2) span').height() ? "p" : "l";
    var img2Format = $('#overview #block6 div:nth-child(3) span').width() < $('#overview #block6 div:nth-child(3) span').height() ? "p" : "l";

    /* Determine which combination of images we have in our #block6/MODEL07 */
    var imgCombo = img1Format + img2Format;

    /* Remove and add classes to restyle #block6 content */

    switch (imgCombo) {
        case 'pp':
        case 'll':
            $('#overview #block6 div:nth-child(2)').not(":last").addClass('append-1');
            /* previous line also adds append-1 to child element, which it should not. Remove it again. */
            $('#overview #block6 div:nth-child(2) div').removeClass('append-1');
            break;
        case 'pl':
            $('#overview #block6 div:nth-child(2)').not(":last").removeClass('span-7');
            $('#overview #block6 div:nth-child(2)').not(":last").removeClass('append-1');
            $('#overview #block6 div:nth-child(2)').not(":last").addClass('span-8');
            break;
        case 'lp':
            $('#overview #block6 div:nth-child(3)').removeClass('span-7');
            $('#overview #block6 div:nth-child(3)').addClass('span-8');
            break;
        default:
    }



    /*********************************************************************************************************
    * Add curly design to toplister
    * Image container is square, yet images are portrait or landscape. Instead of filling the wrapper with the image (and therefore clipping the image) 
    * we add some curly image styling to the wrappers. Code checks for landscape or portrait and applies a suitable curly image to the wrapper.
    */

    /* Get all the images in the toplister */
    var lcount = 0;
    var pcount = 0;

    $('.topLister li div').each(
			function something() {
			    var imgFormat = $(this).find('a img').width() < $(this).find('a img').height() ? 'p' : 'l';

			    if (imgFormat == 'p') {
			        $(this).addClass('curly-p' + pcount);
			        pcount++;
			        if (pcount > 2) { pcount = 0; }
			    }
			    if (imgFormat == 'l') {
			        $(this).addClass('curly-l' + lcount);
			        lcount++;
			        if (lcount > 2) { lcount = 0; }
			    }
			}

		);

    /*********************************************************************************************************
    * Add curly design to article navigation in case there are no images.
    */

    /* DISABLED OMDAT FF TABEL TE HOOG RENDERT : 63px ipv 60px */
    //	$('#artNavTopWrapper3 td.thumb:empty').each(
    //		function something() {
    //
    // Pick 1 random image from a set of 5 images
    //			var rndImageNr = Math.floor(5 * Math.random())

    // Apply image to empty container.
    //			$(this).css('background-image', 'url(/Assets/Img/curly-s' + rndImageNr + '.gif)');

    //		}
    //	);



    /*********************************************************************************************************
    * Replace unloaded (onerror) images with standard images.
    * Currently disabled to due flakey support across various browsers.
    */
    /*
    $('img').each(

	function() {
    obj = this;
    obj.loaded = function() { obj.src = 'http://localhost/she/assets/img/stop-L3-model1.png';  }
    }

	);
    */


    /*********************************************************************************************************
    * Helliptisize text blocks (TEST).
    */

    $('.hellip').each(
		function() {
		    //TEMPhelliptisize($(this).attr('id'));
		    TEMPhelliptisize(this);
		}
	);

});

/*********************************************************************************************************
* Pulldownmenu in navigatiebalk aanklikbaar maken 
*/

function BindPullDownMenu() {
    var userMenuWidth = $('a.buttonPullDown').width();
    var buttonMenuWidth = $('div.buttonMenu').width();
    var paddingCompensation = 27;

    /*  set position of buttonMenu (depended on width of username and some padding styling in .buttonPullDown) */
    $('div.buttonMenu').attr('style', 'right:' + (userMenuWidth - buttonMenuWidth + paddingCompensation) + "px");

    total = userMenuWidth + buttonMenuWidth + paddingCompensation

    $('.buttonPullDown').click(function() {
        $('.buttonMenu').toggleClass('buttonMenuShow');
        return false;
    });
    $('html').click(function() {
        $('.buttonMenu').removeClass('buttonMenuShow');
        // return false;
    });

}

/*********************************************************************************************************
* Start lazyload of images.
*/

/*$(document).ready(function() {
$("img:not(li.slide img)").lazyload({
effect: "fadeIn"
});
});*/




/********************************************************************************************************************/



/*********************************************************************************************************
* Cookies for reading, writing and deleting cookies.
*
* @author		Roger Hamelers
*/

function readCookie(name) {
    var cookieValue = "";
    var search = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) end = document.cookie.length;
            cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}

// Example:
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.

function writeCookie(name, value, hours) {
    var expire = "";
    if (hours != null) {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expire;
}


function deleteCookie(name) {
    document.cookie = name + "=" + "; expires=Fri, 14 Oct 2005 12:00:00 UTC";
}

//-------------------//
//  Dynamic Content  //
//-------------------//
//reg menu
function LoadLoginStatusWidget() {
    $.get('ajaxhttpHandler.ashx?command=getLoginStatusWidget', function(data) {
        if (data != "") {
            $("#regmenu").append(data);
            BindPullDownMenu();
        }
    });
}

//LoadLoginStatusWidget();

/*********************************************************************************************************
* Comments trigger
*
*/

if ($('#commentswrapper').is(':visible')) {
    $('#commenttrigger').css('display', 'none');
}

(function($) {
    //-------------------//
    //  comments plugin  //
    //-------------------//
    $.fn.w3_comments = function(options) {

        var defaults = {
            c_aid: 0,
            c_objk: 30,
            c_count: 0,
            c_taken: 0,
            c_take: 1
        };
        var options = $.extend(defaults, options);

        return this.each(function() {
            //alert(options.c_aid + " " + options.c_objk + " " + options.c_count + " " + options.c_taken + " " + options.c_take);
            $("#morecomment").click(function() {
                $.get('ajaxhttpHandler.ashx?command=getcomments&aid=' + options.c_aid + '&ok=' + options.c_objk + '&co=' + options.c_count + '&si=' + options.c_taken + '&asc=0' + '&take=' + options.c_take, function(data) {
                    if (data != "") {
                        $("#commentsul").append(data);
                        $("#commentsul").append($("li.c2a"));
                        $("li.c2a").show();
                        options.c_taken = $("#commentsul li").size();
                        if (options.c_count == options.c_taken) {
                            $("#morecomment").hide();
                        }
                    }
                });
            })
        })
    }

    /*********************************************************************************************************
    * Fade Breaking News Images
    *
    * @author		Roger Hamelers
    */

    //--------------//
    //  car plugin  //
    //--------------//
    $.fn.w3_3CarBox = function(options) {

        var defaults = {
            animate: true,
            auto: true
        };
        var options = $.extend(defaults, options);


        return this.each(function() {
            //fields
            var i = 1;
            var busy = false;
            var activeItem = null;

            //Hover function
            $(this).children("div.slide").hover(function() {
                busy = true;
                if (activeItem != $(this)) {
                    i = $(this).parent().children("div.slide").index(this) + 1;

                    activeItem = $(this);
                    //hide/show
                    $(this).parent().children("div.slide").children("div.mainImage").hide();
                    $(this).children("div.mainImage").show();

                    //css
                    $(this).parent().children("div.slide").removeClass("active");
                    $(this).addClass("active");
                }
            }, function() {
                busy = false;
            });

            //Timer function
            if (options.auto) {
                $(this).everyTime(3000, 'controlled', function() {
                    if (!busy) {
                        if (i == 3) { i = 0; }
                        //animation
                        if (options.animate) {
                            //$(this).children("div.bidimage").children("div.mainImage").fadeOut("fast");
                            //$(this).children("div.bidimage:eq(" + i + ")").children("div.mainImage").fadeIn("fast");
                            $(this).children("div.slide").children("div.mainImage").fadeOut("slow");
                            $(this).children("div.slide:eq(" + i + ")").children("div.mainImage").fadeIn("slow");
                        }
                        activeItem = $(this).children("div.slide:eq(" + i + ")");
                        //css
                        $(this).children("div.slide").removeClass("active");
                        $(this).children("div.slide:eq(" + i + ")").addClass("active");
                        i++;

                    }
                });
            }

        });
    };
})(jQuery);

$().ready(function() {
    /* $("div#breakingNews div.slide:eq(0)").addClass("active"); */
    /* $("div#breakingNews").w3_3CarBox({ auto: true, animate: true }); */
});







//For clicking the corresponding button when click on the enter key
function clickButton(e, buttonid) {
    var evt = e ? e : window.event;
    var bt = document.getElementById(buttonid);

    if (bt) {
        if (evt.keyCode == 13) {
            bt.click();
            return false;
        }
    }
}



/*********************************************************************************************************
* Some vbscript like functions
*
* @author		Roger Hamelers
*/


function left(txt, length) {
    return txt.substring(0, length);
}

function right(txt, length) {
    return txt.substring(txt.length - length, txt.length);
}

function mid(str, start, len) {

    // Make sure start and len are within proper bounds
    if (start < 0 || len < 0) return "";

    var iEnd, iLen = String(str).length;
    if (start + len > iLen)
        iEnd = iLen;
    else
        iEnd = start + len;

    return String(str).substring(start, iEnd);
}


/*********************************************************************************************************
* Helliptisize
*
* @author		-
*/

function TEMPhelliptisize(p) {

    //if (document.getElementById(id)) {
    //p = document.getElementById(id); 

    //width fix for IE
    //if (navigator.appVersion.indexOf("MSIE") != -1)
    //	p.style.width = '95%';

    var h = p.clientHeight;

    if (h && p.scrollHeight > h) {

        var s = [p], e, o, q, l;
        while ((e = s.pop()))
            do {
            switch (e.nodeType) {
                case 1:
                    if ((o = e.previousSibling))
                        s.push(o);
                    e = e.lastChild;
                    break;
                case 3:
                    if (/[^\t\n\r ]/.test(e.data)) {
                        q = e.nodeValue;
                        l = Math.floor((q.length * h) / p.scrollHeight) - 1;
                        if (l > 0) {
                            do {
                                e.nodeValue = q.substr(0, --l) + '...';

                            } while (l && p.scrollHeight > h);

                            if (l > 0)
                                return



                        }
                        ;
                        e.nodeValue = '';
                    }
                    ;
                default:
                    e = e.previousSibling;
            }
        } while (e)
    }
    //}

}

/*********************************************************************************************************
* Function to rearrange text blocks next to XL IMU, when that XL IMU is not available 
*/

function rearrangeBlocks() {

    $('#leftSide').css('display', 'none');
    $('#rightSide').css('width', '940px');
    $('#rightSide > div').css('float', 'left');
    $('#rightSide > div').css('width', '48%');
    $('#rightSide > div').css('margin-right', '2%');
    $('#rightSide > div + div').css('width', '50%');
    $('#rightSide > div + div').css('margin-right', '0');


}







/* Fireworks script voor horoscoop hover */

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}
function MM_nbGroup(event, grpName) { //v6.0
    var i, img, nbArr, args = MM_nbGroup.arguments;
    if (event == "init" && args.length > 2) {
        if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
            img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
            if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
            nbArr[nbArr.length] = img;
            for (i = 4; i < args.length - 1; i += 2) if ((img = MM_findObj(args[i])) != null) {
                if (!img.MM_up) img.MM_up = img.src;
                img.src = img.MM_dn = args[i + 1];
                nbArr[nbArr.length] = img;
            }
        }
    } else if (event == "over") {
        document.MM_nbOver = nbArr = new Array();
        for (i = 1; i < args.length - 1; i += 3) if ((img = MM_findObj(args[i])) != null) {
            if (!img.MM_up) img.MM_up = img.src;
            img.src = (img.MM_dn && args[i + 2]) ? args[i + 2] : ((args[i + 1]) ? args[i + 1] : img.MM_up);
            nbArr[nbArr.length] = img;
        }
    } else if (event == "out") {
        for (i = 0; i < document.MM_nbOver.length; i++) { img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
    } else if (event == "down") {
        nbArr = document[grpName];
        if (nbArr) for (i = 0; i < nbArr.length; i++) { img = nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
        document[grpName] = nbArr = new Array();
        for (i = 2; i < args.length - 1; i += 2) if ((img = MM_findObj(args[i])) != null) {
            if (!img.MM_up) img.MM_up = img.src;
            img.src = img.MM_dn = (args[i + 1]) ? args[i + 1] : img.MM_up;
            nbArr[nbArr.length] = img;
        }
    }
}

function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}


/**
* Voeg extra styling toe aan ads (extra witruimte)
* skyscraperHome -> skyscraper op homepage
* skyscraperSearch -> skyscraper op zoekpagina
*/

(function(d) {

    /* Placeholders moeten ID's zijn zonder #. Nog workaround vinden hiervoor. */
    var adPlaceHolders = [
			'block1Right .halfpage',
			'skyscraper',
			'block1Right .imu',
			'block3 .xl-imu',
			'integratiesWrapper div',
			'integratiesWrapper',
			'content2 .halfpage'
		];

    function fixWrappers() {

        $.each(adPlaceHolders, function _f() {

            /* We controleren op 50, omdat er een pixel wordt geladen als er geen banner is, en IE neemt daarvoor (te)veel ruimte in */

            currentPlaceHolder = "#" + this;

            if ($(currentPlaceHolder).height() > 50) {
                $(currentPlaceHolder).addClass("advertLoaded");
            } else {
                //console.log(currentPlaceHolder);
                $(currentPlaceHolder).addClass("advertNotLoaded");
                /*$("#" + this).css("display", "none");*/

                /* If xl-imu is not loaded, then rearrange text blocks */
                if (currentPlaceHolder == "#block3 .xl-imu") { rearrangeBlocks() }

                /* If there is no skyscraper then we must reposition integratie160 to top of page. */
                if (currentPlaceHolder == "#skyscraper") { $('#integratie160x160').css('top', '90px'); }

                /* If one or more integratieWrappers have content, then all the other empty integratieWrappers get a backgroundimage. */
                if (currentPlaceHolder == "#integratiesWrapper div") {
                    setIntegratieStoppers();
                }
            }
        });

    }


    function setIntegratieStoppers() {

        if ($('#integratiesWrapper').height() > 50) {
            var objects = $('#integratiesWrapper div.advertNotLoaded');
            var count = objects.length;
            var stoppers = ['stopper-280x80-1.jpg', 'stopper-280x80-2.jpg', 'stopper-280x80-3.jpg'];
            var teller = 0;

            for (i = 0; i < count; i++) {
                //console.log($(objects[i]));
                $(objects[i]).css('height', '80px');
                $(objects[i]).addClass('stopper' + (i + 1));
            }
        }
    }

    setTimeout(fixWrappers, 100);


    //TEST $('#keywordsCompactWrapper').insertAfter($('#keywordsAmpleWrapper'));


} (document));

