var _closeText;  // localized elsewhere..
var _viewFlickr;
var _linkFlickr; //'http://www.flickr.com/photos/stenaline/'
var _viewYoutube; // 'Se filmer på youtube'
var _linkYoutube; // 'http://www.youtube.com/stenaline'
window.youtubeDescriptions = [];
window.flickerDescriptions = [];
window.pendingYoutubeCall = 0;
window.trigger = false;
var youtubeRegexp = /^(http:\/\/)?(?:www\.youtube\.com\/)?(watch\?v=)?([\w-]+)(&{1}[\w=]+){1}$/i;
var gdataRegexp = /^http:\/\/gdata\.youtube\.com\/feeds\/videos\/(\.*)$/i;
var flickerRegexp = /^(?:http:\/\/)?(?:farm(1|2|3|4)\.static\.flickr\.com\/)?([\d]+)\/([\d]+_?[\da-z]+)_{0,1}(?:sq|t|s|m|l|o)?\.(jpg){1}/i;


function runYouTubePP() {
    j$("a[rel='filmer']").each(
			function() {
			    // get the url
			    var url = j$(this).attr("href");
			    // extract the movie clip id 
			    var matchResult = url.match(youtubeRegexp);
			    var id = matchResult[3];

			    var info = window.youtubeDescriptions[id] == undefined ? { info: "", title: ""} : window.youtubeDescriptions[id];

			    j$(this).prettyPhoto({
			        animationSpeed: 'normal',
			        padding: 40,
			        opacity: 0.5,
			        showTitle: true,
			        allowresize: false,
			        theme: 'light_square',
			        linkText: _viewYoutube,
			        link: _linkYoutube,
			        title: info.title,
			        description: info.description,
			        CloseText: _closeText
			    });
			}
		);
}

function runFlickerPP() {
    j$("a[rel='bilder']").each(function() {
        j$(this).prettyPhoto({
            animationSpeed: 'normal',
            padding: 40,
            opacity: 0.6,
            showTitle: true,
            allowresize: false,
            theme: 'light_square',
            linkText: _viewFlickr,
            link: _linkFlickr,
            CloseText: _closeText
        });
    });
}
/*Function to handle flicker url and build mark up for lightBox
arguments are adr = the url from flicker , def = is the source of the default picture if image url is not processable ,
ele = element class or id to input markup in to */
function getFlick(adr, def, ele) {
    var url, arr, size, name, number, loong;
    adr = j$.trim(adr);
    if (flickerRegexp.test(adr)) {
        arr = adr.match(flickerRegexp);
        loong = arr.length;
        size = loong - 1;
        number = loong - 2;
        name = loong - 3;
        url = '<a rel="bilder" href="http://farm1.static.flickr.com/' + arr[2] + '/' + arr[3] + '.jpg"><img width="124px" height="112px" src="http://farm1.static.flickr.com/' + arr[2] + '/' + arr[3] + '_s.jpg"/></a>';
        j$(ele).append(url);
    } else {
        url = '<a href="#"><img src="' + def + '" width="124px" height="112px" alt=""/></a>';
        j$(ele).append(url);
    }
}

function getYouTube(adr, def, ele) {
    var url, arr, size, name, number, loong;
    adr = j$.trim(adr);
    if (youtubeRegexp.test(adr)) {
        arr = adr.match(youtubeRegexp);
        loong = arr.length;
        size = loong - 1;
        number = loong - 2;
        name = loong - 3;
        url = '<a rel="filmer" href="' + arr[0] + '"><img src="http://i1.ytimg.com/vi/' + arr[3] + '/hqdefault.jpg" width="124px" height="112px" alt=""/></a>';
        j$(ele).append(url);
    } else {
        url = '<a href="#"><img src="' + def + '" width="124px" height="112px" alt=""/></a>';
        j$(ele).append(url);
    }
}

/*the following checks if page has id is available, and executes the corresponding code
this should be broken out and done in the site native way  */
function addDescription(data) {
    window.pendingYoutubeCall--;
    // get the url
    var url = data.feed.entry[0].link[0].href;
    // extract the movie clip id 
    var matchResult = url.match(youtubeRegexp);
    var id = matchResult[3];
    var description = data.feed.entry[0].media$group.media$description.$t;
    var title = data.feed.entry[0].title.$t;
    info = { description: "", title: "" };
    info.description = description;
    info.title = title;
    window.youtubeDescriptions[id] = info;
    // if no outstanding calls to youtubes
    if (window.pendingYoutubeCall == 0) {
        runYouTubePP();
    }
}

j$(function() {
    j$(window).load(function() {
        var trigger = false;
        if (j$(".pressReleaseClip").length > 0) {
            j$(".clipBox").removeClass("hidden");
            j$(".pressReleaseClip").each(function() {
                var url = j$(this).val();
                // extract the movie clip id 
                var matchResult = url.match(youtubeRegexp);
                var id = matchResult[3];

                // append the script tag that fetches the json data for the clip 
                var scriptTag = '<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/Stenaline/uploads?alt=json-in-script&format=5&callback=addDescription&q=' + id + '"></script>';
                j$('body').prepend(scriptTag)
                window.pendingYoutubeCall++;

                // create the image
                getYouTube(url, '', '.pressMediaClips');
                trigger = true;
            });
        }
        if (j$(".pressReleaseImage").length > 0) {
            j$(".imageBox").removeClass("hidden");
            j$(".pressReleaseImage").each(function() {
                var href = j$(this).val();
                getFlick(href, '', '.pressMediaImages');
                trigger = true;
            });
        }
        if (j$('#flicker1').length >= 1) {
            getFlick(j$('#flicker1').val(), '', '.mediacontainerFLICKER');
            trigger = true;
        }
        if (j$('#flicker2').length >= 1) {
            getFlick(j$('#flicker2').val(), '', '.mediacontainerFLICKER');
            trigger = true;
        }

        if (j$('#youTube1').length >= 1) {
            // get the url
            var url = j$('#youTube1').val();
            // extract the movie clip id 
            var matchResult = url.match(youtubeRegexp);
            var id = matchResult[3];

            // append the script tag that fetches the json data for the clip 
            var scriptTag = '<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/Stenaline/uploads?alt=json-in-script&format=5&callback=addDescription&q=' + id + '"></script>';
            j$('body').prepend(scriptTag)
            pendingYoutubeCall++;

            // create the image
            getYouTube(url, '', '.mediacontainerYouTube');
            trigger = true;
        }

        if (j$('#youTube2').length >= 1) {
            // get the url
            var url = j$('#youTube2').val();
            // extract the movie clip id 
            var matchResult = url.match(youtubeRegexp);
            var id = matchResult[3];

            // append the script tag that fetches the json data for the clip 
            var scriptTag = '<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/Stenaline/uploads?alt=json-in-script&format=5&callback=addDescription&q=' + id + '"></script>';
            j$('body').prepend(scriptTag);
            pendingYoutubeCall++;

            // create the image
            getYouTube(url, '', '.mediacontainerYouTube');
            trigger = true;
        }

        if (j$('#PressrelRIGHTBoxFLICKER').length >= 1) {
            getFlick(j$('#flicker1').val(), '', '#PressrelRIGHTBoxFLICKER');
            trigger = true;
        }
        if (j$('#PressrelRIGHTBoxYouTUBE').length >= 1) {
            getYouTube(j$('#youTube1').val(), '', '#PressrelRIGHTBoxYouTUBE');
            trigger = true;
        }


        /* This is only used on the start page and the corresponding plugin is slideLite.js
        all settings is commented out as a example to what is available*/

        if (j$('#startPageFlipImage').length >= 1) {
            j$('#startPageFlipImage').cycle({
                timeout: 4500,  // milliseconds between slide transitions (0 to disable auto advance) 
                // speed:         1000,  // speed of the transition (any valid fx speed value) 
                // next:          null,  // id of element to use as click trigger for next slide 
                // prev:          null,  // id of element to use as click trigger for previous slide 
                // before:        null,  // transition callback (scope set to element to be shown) 
                // after:         null,  // transition callback (scope set to element that was shown) 
                // height:       'auto', // container height 
                // sync:          1,     // true if in/out transitions should occur simultaneously 
                // fit:           0,     // force slides to fit container 
                pause:          true     // true to enable "pause on hover" 
                // delay:         0,     // additional delay (in ms) for first transition (hint: can be negative) 
                // slideExpr:     null   // expression for selecting slides (if something other than all children is required) 
            });
        }
        runFlickerPP();
    });

    j$(this).find("a[target='lightbox']").each(function() {
        var href = this.href;

        if (href.slice(-1) == "#") {
            href = href.slice(0, -1);
        }

        var separator = (href.indexOf("?") == -1) ? "?" : "&";

        href += separator + "lbp=1&iframe=true";

        this.href = href;
        j$(this).prettyPhoto({
            animationSpeed: 'normal',
            padding: 40,
            opacity: 0.5,
            showTitle: true,
            allowresize: false,
            theme: 'light_square',
            linkText: '',
            link: '',
            title: '',
            description: '',
            CloseText: _closeText
        });
    });
});

