
// Init KiSS interface
jQuery(document).ready(function(jQuery) {
    // make add-to-any widgets close if you click on them second time
    var lastClicked = false,
        addToAnyPopupVisible = false;        
    
    var addToAnyPopupEl = jQuery('#a2apage_border');
    jQuery('body').click(function(){
        addToAnyPopupVisible = addToAnyPopupEl.is(':visible');
    });
    
    jQuery('a.addtoany_share_save').click(function(){
        if (lastClicked == this && addToAnyPopupVisible){
            jQuery('#a2apage_border, #a2apage_dropdown').css('display', 'none');
            lastClicked = false;
        } else {
            lastClicked = this;
        }        
    });
    // end of add-to-any widget hacks    
    
    KISS.spotlightTabs();
    if (jQuery("#gallery").length) {
        KISS.gallery();
    }
    KISS.openInPopup(jQuery('#footer a.popup'), 800, 640, 100, ',scrollbars=1');
    KISS.openInPopup(jQuery('a.listen-live'), 800, 450, 100, ',scrollbars=no,menubar=no,resizable=no,toolbar=no,location=no,status=no');
    KISS.openInNewWindow(jQuery('a.new-window, div.post a.map-it, div.join-team a'));
    KISS.setupComments();
    KISS.setupFormValidate();

    jQuery('div.post div.links li:first-child, div.comments .list li:first-child, div.latest-comments ul li:first-child').addClass('first');

	/* Setup comment video player */
	jQuery('a.comment-attachment-video').each(function(idx, elm){
		var elm = jQuery(elm);
		var playerContainerId = 'comment-video-player-' + idx;
		elm.before('<div id="' + playerContainerId + '" class="comment-player"></div>');

		var wrapper = jQuery('#' + playerContainerId);
		wrapper.css('height', wrapper.width()*2/3 + 'px');

		var so = new SWFObject('/wp-content/themes/kiss/_ui/js/player/player-viral.swf','mpl',wrapper.width(), wrapper.height(),'9');
		so.addParam('allowfullscreen','true');
		so.addParam('allowscriptaccess','always');
		so.addParam('wmode','opaque');
		so.addVariable('file', elm.attr('href'));
		so.addVariable('backcolor','EEEEEE');
		so.addVariable('frontcolor','999999');
		so.addVariable('lightcolor','111111');
		so.addVariable('screencolor','333333');
		so.write(playerContainerId);
	});

	/* Setup comment audio player */
	jQuery('a.comment-attachment-audio').each(function(idx, elm){
		var elm = jQuery(elm);
		var playerContainerId = 'comment-audio-player-' + idx;
		elm.before('<div id="' + playerContainerId + '" class="comment-player"></div>');

		var wrapper = jQuery('#' + playerContainerId);

		var so = new SWFObject('/wp-content/themes/kiss/_ui/js/player/player-viral.swf','py',wrapper.width(), wrapper.height(),'9');
		so.addParam('allowfullscreen','true');
		so.addParam('allowscriptaccess','always');
		so.addParam('wmode','opaque');
		so.addVariable('file', elm.attr('href'));
		so.addVariable('backcolor','EEEEEE');
		so.addVariable('frontcolor','999999');
		so.addVariable('lightcolor','111111');
		so.addVariable('screencolor','333333');
		so.write(playerContainerId);
	});


	/* Open download links in another page */
	jQuery('a.comment-attachment-image, a.comment-attachment-file, a.comment-attachment-video, a.comment-attachment-audio').click(function(){
		window.open(jQuery(this).attr('href'));
		return false;
	});
	
	// Fix iframe refresh bug
	jQuery('iframe').each(function () {
        this.src = this.src + '&random=' + new Date().getTime();
	});
});

// Load background pattern last
jQuery(window).load(function() {
    jQuery('div.pattern').addClass('show-pattern');
});

// Kiss925.com User interface
var KISS = {

    /**
     * Spotlight tabs
     */
    spotlightTabs: function () {
        var spotlight = jQuery('#spotlight');
        if (spotlight.length) {
            spotlight.tabs({ fx: { opacity: 'toggle', duration: 800} });
            spotlight.tabs('rotate', 7000);
        }
    },

    /**
     * Open link in popup window
     */
    openInPopup: function (items, width, height, top, param) {
        var left = (jQuery('body').width() / 2) - width / 2 - 20;
        jQuery(items).click(function(){
            window.open(this.href, 'name', 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + param);
            return false;
        });
    },

    /**
     * Open link in new window
     */
    openInNewWindow: function (elements) {
        elements.click(function(){
            window.open(this.href);
            return false;
        });
    },

    /**
     * Gallery
     */
    gallery: function () {

        // Initially set opacity on thumbs and add
        // additional styling for hover effect on thumbs
        var onMouseOutOpacity = 0.67;

        jQuery('#thumbs ul.thumbs li').opacityrollover({
            mouseOutOpacity:   onMouseOutOpacity,
            mouseOverOpacity:  1.0,
            fadeSpeed:         'fast',
            exemptionSelector: '.selected'
        });

        // Initialize Advanced Galleriffic Gallery
        var gallery = jQuery('#thumbs').galleriffic({
            delay:                     4000,
            numThumbs:                 6,
            preloadAhead:              6,
            enableTopPager:            false,
            enableBottomPager:         false,
            imageContainerSel:         '#slideshow',
            controlsContainerSel:      '#controls',
            captionContainerSel:       '#caption',
            loadingContainerSel:       '#loading',
            renderSSControls:          true,
            renderNavControls:         true,
            playLinkText:              'Play',
            pauseLinkText:             'Pause',
            prevLinkText:              '&lsaquo; Previous',
            nextLinkText:              'Next &rsaquo;',
            nextPageLinkText:          'Next &rsaquo;',
            prevPageLinkText:          '&lsaquo; Prev',
            enableHistory:             false,
            enableKeyboardNavigation:  false,
            autoStart:                 false,
            syncTransitions:           true,
            defaultTransitionDuration: 1500,
            onSlideChange:             function(prevIndex, nextIndex) {
                // 'this' refers to the gallery, which is an extension of jQuery('#thumbs')
                this.find('ul.thumbs').children()
                    .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                    .eq(nextIndex).fadeTo('fast', 1.0);

                // Update the photo index display
                jQuery('#photo-index').html((nextIndex + 1) +' of '+ this.data.length);
            },

            onPageTransitionOut: function(callback) {
                this.fadeTo('fast', 0.0, callback);
            },

            onPageTransitionIn: function() {

                var total = this.data.length;

                // Hide pager if gallery has less photos than numThumbs
                if (total <= this.numThumbs) {
                    jQuery('#gallery ul.pager').hide();
                } else {
                    var from, to;
                    var numPages = this.getNumPages();
                    var currentPageIndex = this.getCurrentPage();
                    var currentPage = currentPageIndex + 1;

                    var from = currentPageIndex * this.numThumbs + 1;

                    if (currentPage == numPages) {
                        to = total;
                    } else {
                        to = currentPage * this.numThumbs;
                    }

                    jQuery('#gallery ul.pager li.number').text(from + ' - ' + to + ' of ' + total);

                }
                this.fadeTo('fast', 1.0);
            },

            onTransitionOut: function(slide, caption, isSync, callback) {
                slide.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0, callback);
            },

            onTransitionIn: function(slide, caption, isSync, imageData) {
                var duration = this.getDefaultTransitionDuration(isSync);
                slide.fadeTo(duration, 1.0);

                // Position the caption at the bottom of the image and set its opacity
                var slideImage = slide.find('img');
                caption.fadeTo(duration, 1.0);

                // Fix vertical centering in IE6
                if (jQuery.browser.msie && jQuery.browser.version == 6) {
                    var slideImage = slide.find('img');
                    var top = Math.floor((slide.height() - slideImage.outerHeight()) / 2);
                    slideImage.css({ 'margin-top' : Math.floor((slide.height() - slideImage.outerHeight()) / 2) });
                }

                var url = imageData.slideUrl;

                // Insert a video if we have url to youtube, not image
                if (url.match(/^http:\/\/www\.youtube\.com\//)){
                    slide.find('a.advance-link')
                        .attr('href', url)
                        .youtubin({
                            swfWidth : 421,
                            swfHeight : 316
                        });
                }
            }
        });

        /* Event handlers for custom first, next, prev and last page links */
        var pager = gallery.find('ul.pager');
        var last = gallery.data.length - 1;

        pager.find('li.prev a').click(function(e) {
            gallery.previousPage();
            return false;
        });

        pager.find('li.next a').click(function(e) {
            gallery.nextPage();
            return false;
        });

        pager.find('li.first a').click(function(e) {
            gallery.gotoIndex(0);
            return false;
        });

        pager.find('li.last a').click(function(e) {
            gallery.gotoIndex(last);
            return false;
        });
        // More galleries highlighting method
        var more_thumbs = jQuery('div.galleries div.more li a.thumb');
        more_thumbs.css('opacity', 0.75);
        more_thumbs.hover(
          function () {
            jQuery(this).fadeTo('fast', 1.0);
          }, 
          function () {
            jQuery(this).fadeTo('fast', 0.75);
          }
       );
        
    },

    setupComments: function(){
		var formRespond = jQuery('#respond');

        // if #respond show form
        var url = window.location.toString();
        if( (url.indexOf('#respond') != -1) || (url.indexOf('#commentform') != -1) ) {
            formRespond.show();
        } else {
            formRespond.hide();
		}

		jQuery("a[href$='#respond']").click(function(){
            formRespond.show();
        });

		/* comments on gallery */
        var elm = jQuery('.galleries .comments');
        if(elm.size() > 0 ) {

			elm.find('.top .see-all a').click(function(){
				elm.find('.list').toggleClass('list-all');
				return false;
			});
		}

    },

    /*
     * Setup validate
     */
    setupFormValidate: function(){

        var changed = false;

        jQuery('#commentform').each(function(){
            var elm = jQuery(this);
            elm.validate();
            elm.change(function(){
                changed = true;
            });
            confirmReset(elm);
        });

        jQuery('div.mmf').each(function(){
            var elm = jQuery(this);
            elm.change(function(){
                changed = true;
            });
            confirmReset(elm);
        });

        // Confirm that user wants to reset form
        function confirmReset(elm) {
            elm.find('input[type=reset]').click(function(){
                // Test if user changed something in the form
                if (changed) {
                    if ( confirm('Do you want to discard changes?') ) {
                        elm.clearForm();
                        history.back();
                    }
                } else {
                    elm.clearForm();
                    history.back();
                }
                return false;
            });
        }
    },
    
    StyleSwitcher : {
    	Timeouts : {
    		day: false,
    		night: false
    	},
    	activity: 0,
    	Times : {
    		station: false,
    		day: false,
    		night: false
    	},
    	
    	Wait: {
    		day: 0,
    		night: 0
    	},
    	
    	links: jQuery('link[rel*="style"][rel*="alt"][title], link.alt'),
    	
    	// Setup the Styleswitcher
		setup: function () {
			KISS.StyleSwitcher.Times.station = new Date(KISS.StyleSwitcher.Times.station);
			
			jQuery(document).bind('resize scroll keydown keypress mousemove mousedown click', KISS.StyleSwitcher.delay);
			
			KISS.StyleSwitcher.Wait.day = KISS.StyleSwitcher.calculateTimer('day');
			KISS.StyleSwitcher.Wait.night = KISS.StyleSwitcher.calculateTimer('night');
			
			if (KISS.StyleSwitcher.readCookie() === false) {
				KISS.StyleSwitcher.Timeouts.day = window.setTimeout(function () {
					KISS.StyleSwitcher.change('day');
				}, KISS.StyleSwitcher.Wait.day);
				
				KISS.StyleSwitcher.Timeouts.night = window.setTimeout(function () {
					KISS.StyleSwitcher.change('night');
				}, KISS.StyleSwitcher.Wait.night);
			}
		},
		
		calculateTimer: function (name, noDateCorrection) {
			noDateCorrection = noDateCorrection || false;
			var runAt = new Date(KISS.StyleSwitcher.Times.station);
			runAt.setHours(KISS.StyleSwitcher.Times[name].hour);
			runAt.setMinutes(KISS.StyleSwitcher.Times[name].minute);
			
			// If we went backwards in time
			if (!noDateCorrection && runAt < KISS.StyleSwitcher.Times.station) {
				runAt.setDate(runAt.getDate() + 1);
			}
			
			var offset = runAt - KISS.StyleSwitcher.Times.station;
			
			return offset;
		},
		
		delay: function () {
			KISS.StyleSwitcher.activity = new Date();
		},
		
		flip: function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var newTheme = jQuery(document.body).hasClass('night') ? 'day' : 'night';
			
			KISS.StyleSwitcher.writeCookie(newTheme);
			
			KISS.StyleSwitcher.change(newTheme);
		},
		
		writeCookie: function (value) {
			var expires = new Date(2030, 0, 1);
		
			document.cookie = 'kiss-theme=' + value + '; expires=' + expires.toGMTString() + ';path=/';
		},
		
		readCookie: function () {
			var all = document.cookie.split(';');
			for(var i = 0; i < all.length; i++) {
				var cookie = all[i].split('=');
				
				if (cookie[0] === 'kiss-theme') {
					return cookie[1];
				}
			}
			
			return false;
		},
		
		change: function (name) {
			
			jQuery.scrollTo(0, 1500);
			
			KISS.StyleSwitcher.Timeouts[name] = window.setTimeout(function () {
				KISS.StyleSwitcher.change(name);
			}, 86400000);
			
			KISS.StyleSwitcher.links.each(function () {
				var title = this.getAttribute('title').toLowerCase().replace(/\s/, '-');
				
				this.disabled = true;
				this.setAttribute('rel', 'alternate stylesheet');
				jQuery(document.body).removeClass(title);
				
				if (title === name) {
					jQuery(document.body).addClass(title);
					this.disabled = false;
					this.setAttribute('rel', 'stylesheet');
				}
			});
			
			
			if (jQuery.browser.msie && jQuery.browser.version <= 6) {
				KISS.StyleSwitcher.fixBelatedPNG();
			}
		},
		
		fixBelatedPNG: function () {
			var elements = jQuery(fixPNGSelector);
			
			elements.each(function () {
				if (typeof this.vml !== 'undefined') {
					DD_belatedPNG.vmlFill(this);
					var that = this;
					window.setTimeout(function () {
						DD_belatedPNG.vmlFill(that);
					}, 1000);
				}
				else {
					DD_belatedPNG.fixPng(this);
				}
			});		
		}
	},
	
	StylePeel: {
		Timeouts: {
			peelIn: 0,
			teaseOut: 0,
			expanded: 0,
			open: 0
		},
		setup: function (element) {
			KISS.StylePeel.element = jQuery(element);
			KISS.StylePeel.peel = KISS.StylePeel.element.find('img.peel');
			KISS.StylePeel.back = KISS.StylePeel.element.find('.back')
			
			if (jQuery.browser.msie && jQuery.browser.version <= 6) {
				KISS.StylePeel.fixPNG(KISS.StylePeel.peel);
			}
			
			KISS.StylePeel.element.find('area, span.button').click(function (e) {
				this.blur();
				
				e.stopImmediatePropagation();
				e.preventDefault();
				
				KISS.StyleSwitcher.flip();
			});


			
			KISS.StylePeel.element.find('span.close').click(function (e) {
				e.stopImmediatePropagation();
				e.preventDefault();
				
				KISS.StylePeel.peelIn();
			});
			
			KISS.StylePeel.originalSizes = {
				peel : {
					height: KISS.StylePeel.peel.css('height'),
					width: KISS.StylePeel.peel.css('width')
				},
				back : {
					height: KISS.StylePeel.back.css('height'),
					width: KISS.StylePeel.back.css('width')
				}
			};
			
			KISS.StylePeel.newSizes = {
				peel: {
					height: '428px',
					width: '426px'
				},
				
				back: {
					height: '391px',
					width: '381px'
				}
			};

			KISS.StylePeel.teaseSizes = {
				peel: {
					height: '208px',
					width: '200px'
				},
				
				back: {
					height: '200px',
					width: '200px'
				}
			};

			
			KISS.StylePeel.element.hover(KISS.StylePeel.peelOut, KISS.StylePeel.peelIn);
			
			
			
			//KISS.StylePeel.Timeouts.teaseOut = window.setTimeout(KISS.StylePeel.teaseOut, 5000);
		},
		
		fixPNG: function (img) {
			
			if (img[0].nodeName.toLowerCase() === 'img') {
				var sizingMethod = 'scale',
					pngSrc = img.attr('src'),
					setSrc = true;
			}
			else {
				var sizingMethod = 'image',
					pngSrc = img.css('background-image').replace(/^url\("/, '').replace(/"\)$/, ''),
					setSrc = false;
			}
			
			img.css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=" + sizingMethod + ", src='" + pngSrc + "')");
			
			if (setSrc) {
				img.attr('src', 'wp-content/themes/kiss/_ui/images/trans.gif');
			}
			else {
				img.css('background-image', 'url(wp-content/themes/kiss/_ui/images/trans.gif)');
			}
		},
		
		peelOut: function () {

			window.clearTimeout(KISS.StylePeel.Timeouts.open);
			window.clearTimeout(KISS.StylePeel.Timeouts.expanded);
			window.clearTimeout(KISS.StylePeel.Timeouts.peelIn);
			window.clearTimeout(KISS.StylePeel.Timeouts.teaseOut);
			
			
			KISS.StylePeel.Timeouts.expanded = window.setTimeout(function () {
				KISS.StylePeel.element.addClass('expanded');
			}, 50);
			
			KISS.StylePeel.peel.add(KISS.StylePeel.back).stop();
		
			KISS.StylePeel.peel.animate(KISS.StylePeel.newSizes.peel, 800);
			
			KISS.StylePeel.back.animate(KISS.StylePeel.newSizes.back, 800);
			
			KISS.StylePeel.Timeouts.open = window.setTimeout(function () {
				KISS.StylePeel.element.addClass('open');
			}, 650);
		},
		
		peelIn: function () {
			
			window.clearTimeout(KISS.StylePeel.Timeouts.expanded);
			window.clearTimeout(KISS.StylePeel.Timeouts.open);
			
			KISS.StylePeel.Timeouts.expanded = window.setTimeout(function () {
				KISS.StylePeel.element.removeClass('expanded');
			}, 390);
			
			KISS.StylePeel.Timeouts.open = window.setTimeout(function () {
				KISS.StylePeel.element.removeClass('open');
			}, 150);
			
			KISS.StylePeel.peel.add(KISS.StylePeel.back).stop();
		
			KISS.StylePeel.back.animate(KISS.StylePeel.originalSizes.back, 400);
			KISS.StylePeel.peel.animate(KISS.StylePeel.originalSizes.peel, 400);
			
			
		},
		
		teaseOut: function () {
			if (KISS.StylePeel.img.is(":animated") || KISS.StylePeel.back.is(":animated")) {
				return;
			}
			
			KISS.StylePeel.img.animate(KISS.StylePeel.teaseSizes.img, 500);
			
			KISS.StylePeel.back.animate(KISS.StylePeel.teaseSizes.back, 500, function () {
				KISS.StylePeel.Timeouts.peelIn = window.setTimeout(KISS.StylePeel.peelIn, 2000);
			});
		}
	}
}

function openListenLive(width , height) {
    url = "http://" + window.location.host + "/listen/gateway.php";
    width = width ? width : 800;
    height = height ? height : 450;
    var win = window.open(url, "KiSS925.com Listen Live", "width=" + width + ",height=" + height + ",status=0,scrollbars=0,resizable=0")
    win.focus();
    return false;
}

KISS.StylePeel.setup('#pageflip');