var play;
var swfObjects = {};

function toggleFlashBtn(flashObj, ready) {
    var swfObj = swfObjects[flashObj];

    if (ready) {
	    for (obj in swfObjects) {
	    	if (obj != flashObj) {    		
	    		swfObjects[obj].obj.pauseState();
	    		swfObjects[obj].playState = false;
	    	}
	    }
    } else {
    	if (!swfObj.playState) {
    		swfObj.obj.playState();
    		swfObj.playState = true;
    	}
    	else {
    		swfObj.obj.pauseState();
    		swfObj.playState = false;
    	}
    }
    
}

function pauseAll(flashObj) {
	for (obj in swfObjects) {
		swfObjects[obj].obj.pauseState();
		swfObjects[obj].obj.playState = false;
    }
}

function Tickers() {}

Tickers.prototype = {
    tickerOver: function(ev) {
        $(ev.currentTarget).find(".ticker-artist").animate({
            opacity: 1
        }, {
            queue: false
        });
    },
	
    tickerOut: function(ev) {
        $(ev.currentTarget).find(".ticker-artist").animate({
            opacity: 0
        }, {
            queue: false
        });
    },
	
    ticketArtistOver: function(ev) {
        $(ev.currentTarget).find(".ticker-content-artists, .ticker-content-artists span").animate({
            opacity: 0
        }, {
            queue: false
        });
		
        $(ev.currentTarget).find(".ticker-content-artists-over").animate({
            opacity: 1
        }, {
            queue: false
        });
    },
	
    ticketArtistOut: function(ev) {
        $(ev.currentTarget).find(".ticker-content-artists, .ticker-content-artists span").animate({
            opacity: 1
        }, {
            queue: false
        });
        $(ev.currentTarget).find(".ticker-content-artists-over").animate({
            opacity: 0
        }, {
            queue: false
        });
    },
	
    ticketKunstlerOver: function(ev) {
        $(ev.currentTarget).find(".ticker-content-artists img").animate({
            opacity: 0
        }, {
            queue: false
        });
    },
	
    ticketKunstlerOut: function(ev) {
        $(ev.currentTarget).find(".ticker-content-artists img").animate({
            opacity: 1
        }, {
            queue: false
        });
    },
	
    ticketTextOver: function(ev) {
	$(ev.currentTarget).find(".ticker-text").hide();
        $(ev.currentTarget).find(".ticker-content-artists").show();
    },

    ticketTextOut: function(ev) {
	$(ev.currentTarget).find(".ticker-text").show();
        $(ev.currentTarget).find(".ticker-content-artists").hide();
    }
}

function openPopup(url, name, width, height) {
    var popupObj = {};
    popupObj.url = url;
    popupObj.name = name;
		
    if (width)
        popupObj.width = width;
    if (height)
        popupObj.height = height;
		
    $.openPopupLayer(popupObj);
}

/**
 * 
 * @param formSelector <string> jQuery selector
 * @param errorMessage <string> defaul error message
 * @param asynchronous <boolean>
 * @param inputMailName <array>
 * @return submit form, if asynchronous uses $.ajax request and return a clean html to put above form.
 */
function validateForms(formSelector, errorMessage, asynchronous, inputMailName) {
    this.formSelector = formSelector;
    this.errorMessage = errorMessage;
    this.asynchronous = asynchronous;
	
    if (inputMailName)
        this.inputMailName = inputMailName;
    else
        this.inputMailName = false;
	
    _thisVF = this;
}

validateForms.prototype = {
    notEmpty: function(field) {
        var errorMsg, fieldName;
	
        if ($(field).val().length < 1) {
            if(!_thisVF.errorMessage) {
                fieldName = $(field).attr("alt");
                errorMsg = '<strong>' + fieldName + '</strong> shouldn\'t be blank';
            }
            else
                errorMsg = _thisVF.errorMessage;
			
            if (!$(field).next().is("div.error"))
                $('<div class="error">'+errorMsg+'</div>').insertAfter(field);
            else if ($(field).next().is("div.error"))
                $(field).next().html(errorMsg);
			
            $(field).addClass('inputWithError');
			
            return false;
        }
        else {
            $(field).removeClass('inputWithError');
            if ($(field).next().is("div.error"))
                $(field).next().remove();
			
            return true;
        }
    },
	
    emailFormat: function(field) {
        var errorMsg, fieldName, inputMailName;
		
        if (_thisVF.inputMailName.length > 0)
            inputMailName = _thisVF.inputMailName;
        else
            inputMailName = ['email'];

        if ($.inArray($(field).attr("alt"), inputMailName) != -1) {
            if ($(field).val().length >= 1) {
                var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                if ($(field).val().search(pattern) == -1) {
                    fieldName = $(field).attr("alt");
                    errorMsg = '<strong>' + fieldName + '</strong> format invalid';
					
                    if (!$(field).next().is("div.error"))
                        $('<div class="error">'+errorMsg+'</div>').insertAfter(field);
					
                    $(field).addClass('inputWithError');
					
                    return false;
                }
                return true;
            }
        }
        return true;
    },
	
    submit: function() {
        if(!_thisVF.asynchronous)
            $(_thisVF.formSelector).submit();
        else
            $.ajax({
                type: "POST",
                url: $(_thisVF.formSelector).attr("action"),
                data: $(_thisVF.formSelector).serialize(),
                success: function(html) {
                    $(_thisVF.formSelector).before('<div class="success">'+html+'</div>');
                    $(_thisVF.formSelector).hide();
                },
                error: function(msg) {
                    $(_thisVF.formSelector).before('<div class="error">'+msg.statusText+'</div>');
                }
            })
    },
	
    validateRequired: function() {
        requiredFields = $(this.formSelector + " input.required");
        var error = false;
		
        if (requiredFields.length > 0) {
            requiredFields.each(function() {
                if (!_thisVF.notEmpty(this))
                    error = true;
				
                if (!_thisVF.emailFormat(this))
                    error = true;
            });
        }
		
        if (error)
            return false;
        else
            _thisVF.submit();
		
    }
}

/**
 * 
 * @param targetElement should be a jQuery Selector
 * @param width is an integer
 * @param flashObj flash object
 * @param title is the song title (optional)
 * @param artist is the song author (optional)
 * @return Music Player
 */
function musicPlayer(targetElement, width, flashObj, title, artist) {

    var songData = {}
    if (artist)
        songData['username'] = artist;
    if (title)
        songData['title'] = title;

    $(targetElement).scPlayer({
        width: width,
        collapse: false,
        flashObj: flashObj,
        customData: songData
    });
	
    var targetId = $(targetElement).selector.replace("a.soundcloud-player#music_", "");
    var browserVersion = parseInt($.browser.version);
	
    if ($.browser.msie && browserVersion < 8) {
        $("#pB_" + targetId).before(
            $('<a class="btn-swf-hack bColor1"></a>').click(function() {
                $("#music_" + targetId + " a").click();
            })
            );
    }
}

function ImageSlider() {
    _thisIS = this;
}

ImageSlider.prototype = {
    slider: function() {
        var currentImg = $('#events-img li:visible');
        var nextImg = currentImg.next().length > 0 ? currentImg.next() : $('.events-img li:first');
        currentImg.fadeOut(2000);
        $(nextImg).fadeIn(2000, _thisIS.start);
    },
	
    start: function() {
        if ($('#events-img li').length > 1) {
            setTimeout("_thisIS.slider()", 2000);
        }
    }
}

function DescSlider(sel) {
	this.container = $(sel);
	this.init();
}

DescSlider.prototype = {
	init: function() {
		var _this = this;
		var cnt = _this.container;
		var canv_up = null;
		var canv_dw = null;
		
		if (cnt.find('p').height() > (cnt.find('.box-text-slider').height() + 10)) {
			cnt.find('#btn-slide-up').bind('click', function() {
				_this.slideUp();
			});
			
			cnt.find('#btn-slide-down').bind('click', function() {
				_this.slideDown();
			});
			
			canv_up = document.getElementById('slide-up-arrow');
			canv_dw = document.getElementById('slide-down-arrow');
			
			if (canv_up.getContext) {
				_this.drawUpArrow(canv_up, initialColor2);
			}
			if (canv_dw.getContext) {
				_this.drawDownArrow(canv_dw, initialColor2);
			}
			
			cnt.find('canvas').bind('changeColorArrows', function(e, color1, color2) {
				canv_up.getContext('2d').clearRect(0,0,30,30);
				_this.drawUpArrow(canv_up, color2);
				canv_dw.getContext('2d').clearRect(0,0,30,30);
				_this.drawDownArrow(canv_dw, color2);
			});
		}
	},
	
	slideUp: function() {
		var cnt = this.container;
		if (parseInt(cnt.find('p').css('top')) < 0) {
			cnt.find('p').css({'top': parseInt(cnt.find('p').css('top')) + 80});
			if (parseInt(cnt.find('p').css('top')) > 0) {
				cnt.find('p').css({'top':'0px'});
			}
		}
	},
	
	slideDown: function() {
		var cnt = this.container;
		var slideEnd = cnt.find('.box-text-slider').height() - cnt.find('p').height();
		if (parseInt(cnt.find('p').css('top')) > slideEnd) {
			cnt.find('p').css({'top': parseInt(cnt.find('p').css('top')) - 80});
			if (parseInt(cnt.find('p').css('top')) < slideEnd) {
				cnt.find('p').css({'top': slideEnd});
			}
		}
	},
	
	drawUpArrow: function(ctx, fillColor) {
		ctx = ctx.getContext('2d');
		ctx.beginPath();
		ctx.moveTo(5,26);
		ctx.lineTo(0,26);
		ctx.lineTo(15,4);
		ctx.lineTo(30,26);
		ctx.lineTo(25,26);
		ctx.lineTo(15,10);
		ctx.closePath();
		ctx.fillStyle = fillColor;
		ctx.fill();
	},
	
	drawDownArrow: function(ctx, fillColor) {
		ctx = ctx.getContext('2d');
		ctx.beginPath();
		ctx.moveTo(5,4);
		ctx.lineTo(0,4);
		ctx.lineTo(15,26);
		ctx.lineTo(30,4);
		ctx.lineTo(25,4);
		ctx.lineTo(15,20);
		ctx.closePath();
		ctx.fillStyle = fillColor;
		ctx.fill();
	}
};

function videoPlayButton(options) {
	var defaultOptions = {
		container: "body",
		dimensions: 100,
	};

	this.options = $.extend({}, defaultOptions, options);
	
	this.container = $(this.options.container);
	this.init();
}
videoPlayButton.prototype = {
	init: function() {
		var _this = this;
		var cnt = this.container;
		
		_this.draw(initialColor1, initialColor2);
		
		cnt.find('canvas').bind('changeColorArrows', function(e, color1, color2) {
			_this.draw(color1, color2);
		});
	},
	
	draw: function(arrowColor, bgColor) {
		var _this = this;
		var cnt = this.container;
		var dim = _this.options.dimensions;
		
		cnt.each(function() {
			var canvas = document.getElementById($(this).find('canvas').attr('id'));
			var ctx = canvas.getContext('2d');
			
			ctx.clearRect(0,0,dim,dim);
			ctx.beginPath();
			ctx.arc(dim/2, dim/2, dim/2, 0, Math.PI*2, false);
			ctx.closePath();
			ctx.fillStyle = bgColor;
			ctx.fill();
			ctx.beginPath();
			ctx.moveTo(parseInt(dim/3), parseInt(dim/3.8));
			ctx.lineTo(parseInt(dim/1.2), parseInt(dim/2));
			ctx.lineTo(parseInt(dim/3), parseInt(dim/1.3));
			ctx.closePath();
			ctx.fillStyle = arrowColor;
			ctx.fill();
		});
	}
};


$(document).ready(function(){
    tickers = new Tickers();
	
    $(".ticker").bind("mouseenter", tickers.tickerOver);
    $(".ticker .ticker-artist").css('opacity', 0).show()
    $(".ticker").bind("mouseleave", tickers.tickerOut);
	
    $(".ticket-kunstler").bind("mouseenter", tickers.ticketKunstlerOver)
    $(".ticket-kunstler").bind("mouseleave", tickers.ticketKunstlerOut);
	
    $(".ticket-artist").bind("mouseenter", tickers.ticketArtistOver)
    $(".ticket-artist").bind("mouseleave", tickers.ticketArtistOut);
	
    $(".ticket-text").bind("mouseenter", tickers.ticketTextOver)
    $(".ticket-text").bind("mouseleave", tickers.ticketTextOut);

    $(".ticker-content .club .name").each(function(index) {
        if($(this).outerWidth()>149){
            $(this).css("white-space","normal");
        }
     });
    
    //Hack to load excanvas.js for <canvas> on Internet Explorer.
    if ($.browser.msie) {
	    setTimeout(function() {
	    	var homePodcastButton = new videoPlayButton({
	        	container: ".podcast-home-container",
	        	dimensions: 36
	    	});
	    	var artistProfileSlide = new DescSlider(".scroll-text-container");
	    }, 500);
    } else {
    	//Not IE browsers.
    	var homePodcastButton = new videoPlayButton({
        	container: ".podcast-home-container",
        	dimensions: 36
    	});
    	var artistProfileSlide = new DescSlider(".scroll-text-container");
    }
});
