﻿var Rotator = Rotator || {};

/* Private */
Rotator.slides;
Rotator.timer;
Rotator.groupID;
Rotator.configXML;
Rotator.mode;
Rotator.currentSlide;

/* public */
Rotator.pagerIconOn;
Rotator.pagerIconOff;
Rotator.spacerGif;

Rotator.DURATION_DEFAULT = 12000;

/* display modes */
Rotator.IS_TOUCH_DEVICE = false;

Rotator.init = function () {

    //check for browser detect

    var userAgent = navigator.userAgent.toLowerCase();

    Rotator.IS_TOUCH_DEVICE =  userAgent.match(/android/) || userAgent.match(/iphone/) || userAgent.match(/ipad/) || userAgent.match(/ipod/);

    Rotator.slides = new Array();

    $.ajax({
        type: "GET",
        url: Rotator.configXML,
        dataType: "xml",
        error: function () { Rotator.log('error loading xml'); },
        success: function (xml) {
            Rotator.parseXML(xml);
        }
    });
}


Rotator.parseXML = function (xml) {

    if (!xml) return;

    var group;

    //set pager icons
    Rotator.pagerIconOn = Rotator.tokenizer(Rotator, $(xml).find('on').text());
    Rotator.pagerIconOff = Rotator.tokenizer(Rotator, $(xml).find('off').text());
    Rotator.spacerGif = Rotator.tokenizer(Rotator, $(xml).find('spaceGif').text());


    $(xml).find('group').each(function () {
        if ($(this).attr('id').toLowerCase() == Rotator.groupID.toLowerCase()) {
            group = $(this);
        }
    });

    if (!group) {
        Rotator.log('group not found');
        return;
    }

    group.find('slide').each(function () {

        var slide = new Rotator.Slide();

        slide.src = Rotator.tokenizer(Rotator, $(this).attr('src'));
        slide.duration = $(this).attr('duration');
        slide.duration = (slide.duration) ? slide.duration : Rotator.DURATION_DEFAULT;
        slide.width = $(this).attr('width');
        slide.height = $(this).attr('height');
        slide.vars = $.parseJSON(Rotator.tokenizer(Rotator, $(this).find('vars').text()));
        slide.type = $(this).attr('type');
        slide.x = ($(this).attr('x')) ? $(this).attr('x') : group.attr('defaultX');
        slide.y = ($(this).attr('y')) ? $(this).attr('y') : group.attr('defaultY');
        slide.backUpImage = Rotator.tokenizer(Rotator, $(this).attr('backUpImage'));

        slide.pagerIcon = $('<img>', { 'page-icon-id': slide.guid, 'src': Rotator.pagerIconOff });

        slide.pagerIcon.click(function () {
            Rotator.load(Rotator.getSlideFromGuid($(this).attr('page-icon-id')));
        });

        switch (slide.type) {
            case Rotator.SlideType.IMAGE:
            case Rotator.SlideType.SWF:
            case Rotator.SlideType.HTML:

                if (Rotator.IS_TOUCH_DEVICE && slide.backUpImage) {
                    slide.src = slide.backUpImage;
                    slide.type = Rotator.SlideType.IMAGE;
                    slide.pagerIcon.appendTo($('#pager-container'));
                    Rotator.slides.push(slide);
                } else if (Rotator.IS_TOUCH_DEVICE && slide.type == Rotator.SlideType.IMAGE) {
                    slide.pagerIcon.appendTo($('#pager-container'));
                    Rotator.slides.push(slide);
                } else if (!Rotator.IS_TOUCH_DEVICE) {
                    slide.pagerIcon.appendTo($('#pager-container'));
                    Rotator.slides.push(slide);
                }


                break;
        }
    });

    Rotator.nextSlide();
}

Rotator.nextSlide = function () {

    var guid = $('#pager-container img.active').next().attr('page-icon-id');

    if (!guid) guid = $('#pager-container>img').first().attr('page-icon-id');

    if (guid)
        Rotator.load(Rotator.getSlideFromGuid(guid));
};

Rotator.getSlideFromGuid = function (guid) {

    var slide = {};

    $.each(Rotator.slides, function (index, value) {
        if (value.guid == guid) {
            slide = value;
        }
    });

    return slide;
};

Rotator.updateNav = function (slide) {

    $('#pager-container>img').removeClass('active');
    $('#pager-container>img').attr('src', Rotator.pagerIconOff);

    slide.pagerIcon.addClass('active');
    slide.pagerIcon.attr('src', Rotator.pagerIconOn);
}

Rotator.load = function (slide) {

	if(Rotator.onSwitch != null)
		Rotator.onSwitch();

    if (!slide) return;

    Rotator.updateNav(slide);

    $("#rotator-content").css('top', '0px').css('left', '0px');

    var content = "";

    clearInterval(Rotator.timer);

    Rotator.currentSlide = slide;

    // do browser detect to decide on what content to show.

    switch (slide.type) {
        case Rotator.SlideType.SWF:
            $("#rotator-content").html("<div id='flash-rotator-container'></div>");
			$('#flash-rotator-container').flash({
				swf: slide.src, width: slide.width, height: slide.height, menu: 'false', wmode: 'transparent', id: 'flash-rotator',
				flashvars: slide.vars
			});

            break;

        case Rotator.SlideType.IMAGE:

            if (!slide.vars || !slide.vars.url || !slide.vars.target) Rotator.log('missing vars \'target\' or \'url\'');

            content = "<a href='" + slide.vars.url + "' target='" + slide.vars.target + "'><img border='0' src='" + slide.src + "'></a>";
            $("#rotator-content").html(content);

            break;

        case Rotator.SlideType.HTML:
            // still need to figure this out
            content = "<iframe src='" + slide.src + "' scrolling='no' frameborder='0' width='" + slide.width + "px' height='" + slide.height + "px' style='position:absolute;'></iframe>";
            var div = $("<div>").css('width', slide.width + "px").css('height', slide.height + "px").css('position', 'absolute');
            var image = $('<img>', { src: Rotator.spacerGif, width: slide.width, height: slide.height, border: 0 });
            var anchor = $('<a>', { id: 'thickboxId', href: slide.vars.url, target: slide.vars.target }).html(image);
            div.html(anchor);

            $("#rotator-content").html(content);
            $("#rotator-content").append(div);

            break;
    }


    $("#rotator-content").css('top', slide.y + "px").css('left', slide.x + "px").css('position', 'absolute');

    Rotator.timer = setInterval("Rotator.nextSlide()", slide.duration);

};

/* Helper */

Rotator.tokenizer = function (object, content) {

    if (!object || !content) return;

    for (var token in object) {
        content = content.replaceAll("^^" + token.toString() + "^^", object[token]);
    }

    return content;
}

String.prototype.replaceAll=function(s1, s2) {return this.split(s1).join(s2)}

/* Enums */

Rotator.SlideType = {};
Rotator.SlideType.IMAGE = 'image';
Rotator.SlideType.SWF = 'swf';
Rotator.SlideType.HTML = 'html';

/* Models */

Rotator.Slide = function () {
    this.src;
    this.duration;
    this.guid = Math.round(Math.random() * 1000);
    this.pagerIcon;
    this.vars;
    this.x;
    this.y;
    this.type;
    this.width;
    this.height;
};

/* Log */

Rotator.log = function(message){
	//console.log(message);
}




