﻿window.remoteURL = '/remote/public/?action=';
window.autoUI = false;

$(function () {
    initCustomFunctions();
    doCufon();
    initMenu();

	switch(window.pid) {
		case 1:
			initHome();
			break;
		case 30:
	        initInside();
			initCalendar();
			break;
		default:
	        initInside();
			break;
	}

    initSearch();
    initAudio();
    initTweetBox();
    $('.overlabel').overlabel();
    onResizer();

    $(window).bind('resize', function() {
        onResizer();
    });
});

function doCufon() {
    Cufon.replace('#nav li a, .cwl-accordion h3 a, #map-link .text, .right-column .item h2, #item-blog .title, #item-blog .date, .extruder, #inside h1, .inside-header h2, .jp-title ul li, .cwl-accordion-not h3, #calendar-inside h1, .tab h2, #secondary h3', {
        'hover': true,
        'fontFamily': 'myr'

    });
}

function onResizer() {
    fHeight = $(window).height() - 493;
    $('#inside').css({
        'min-height': fHeight
    });
}

function showLoader() {
    $.fancybox.showActivity();
}

function hideLoader() {
    $.fancybox.hideActivity();
}

function initMenu() {
    jQuery("#nav a").removeAttr('title');
    jQuery("#nav > ul").css({ display: "none" }); // Opera Fix

    $('#nav > li').bind('mouseenter', function () {
        jQuery(this).find('ul:first').css({
            visibility: "visible",
            display: "none"
        }).slideDown(400, "easeInOutQuart");
    });

    $('#nav > li > ul').bind('mouseenter', function () {
        $(this).css({
            'visibility': 'visible'
        });
    });

    $('#nav > li > ul  > li').bind('mouseenter mouseleave', function () {
        $(this).toggleClass('hover');
    });

    $('#nav > li').bind('mouseleave', function () {
        jQuery(this).find('ul:first').css({
            visibility: "hidden"
        });
    });

    $('#nav > li > ul').addClass('shadow');

    $('#nav > li > ul > li:last-child').css({
        'border-bottom-width': '0px'
    });

    $('#nav ul > li:first-child a').each(function() {
        fHref = $(this).attr('href');
        fPID = $(this).attr('pid');
        $(this).parent().parent().parent().find('a:first').attr({
            'href': fHref,
            'pid': fPID
        });
    });
}

function initSlideShow() {
    $('#slidePager').html('');
    if ($('.home #slides').length > 0) {
        $('#slides').cycle({
            fx: 'fade',
            speed: 1750,
            timeout: 7000,
            randomizeEffects: false,
            easing: 'easeOutCubic',
            next: '.slideNext',
            prev: '.slidePrev',
            pager: '#slidePager',
            cleartypeNoBg: true
        });
    }

}

function initCustomFunctions() {
    initCWLAccordions();
    $('#tweetbox > div:last').css('margin-bottom', 0);

    $('.tab .extruder').bind('click', function () {
        if ($(this).parent().hasClass('open')) {
            $(this).parent().animate({
                'height': 0
            }, 500, 'easeOutCubic', function () {
                $(this).removeClass('open');
            });

            $('#section-footer').animate({
                'height': 0
            }, 500, 'easeOutCubic');
        } else {
            fHeight = parseInt($(this).parent().attr('tab-height'));
            $(this).parent().animate({
                'height': fHeight
            }, 500, 'easeOutCubic', function () {
                $(this).addClass('open');
            });

            $('#section-footer').animate({
                'height': fHeight
            }, 500, 'easeOutCubic');
        }
    });
}

function initCWLAccordions() {
    jQuery('.cwl-accordion').each(function () {
        jQuery(this).accordion({
            active: parseInt(getAttr(jQuery(this), 'active', 0)),
            header: "h3",
            autoHeight: getAttr(jQuery(this), 'autoheight', false),
            fillSpace: getAttr(jQuery(this), 'fillspace', false),
            collapsible: getAttr(jQuery(this), 'collapsible', false),
            animated: "bounceslide",
            icons: {
                'header': 'ui-icon-circle-plus',
                'headerSelected': 'ui-icon-circle-minus'
            }
        });

        jQuery(this).removeClass('accordion');
    });
}

function initTweetBox() {
    getTwitters('tweetbox', {
        id: 'CWLTweets',
        count: 15,
        enableLinks: true,
        ignoreReplies: false,
        clearContents: true,
        template: '"%text%" <span class="tweet-time">%time%</span>',
        newWindow: true,
        callback: function () {
            initTweetBoxCycle();
        }
    });
}

function initTweetBoxCycle() {
    fTweetBar = '';
    var fArray = new Array;
    $('#tweetbox ul li').each(function() {
        fArray.push($(this).html());
    });
    
    j = 0;
    fHTML = '';
    for (i=0; i<fArray.length; i++) {
        fTweetBar += '<span class="item">' + fArray[i] + '</span>';
        if (j==0) {
            fHTML += '<li>' + fArray[i] + '<br><br>';
            j = 1;
        } else {
            fHTML += fArray[i] + '</li>';
            j = 0;
        }
    }

    if (j == 1) {
        fHTML += '</li>';
    }

    $('#tweet-bar-content').html(fTweetBar);
    $('#tweetbox ul').html(fHTML);
	doCufon();
    $('#tweetbox ul').cycle({
        fx: 'scrollLeft',
        speed: 800,
        timeout: 7000,
        randomizeEffects: false,
        easing: 'easeOutCubic',
        next: '.slideNext',
        prev: '.slidePrev',
        cleartypeNoBg: true,
        pager: '#tweet-pager'

    });
}

function getTwitterFeedItem(fText, fAuthor, fDate) {
    return '<div>' + fText + '</div>';
}

function initHome() {
    initSlideShow();
    $('#tweet-bar').animate({
        bottom: -35
    }, 2600, 'easeOutQuart');
}



function initInside() {
    if ($('#inside').length > 0) {
        $('#inside > h1 + p:eq(0)').animate({
            'padding-top': 20
        }, 1200, 'easeOutQuart');

        $('#inside > p + h1').each(function () {
            fI = $(this).index() - 1;
            $('#inside > *:eq(' + fI + ')').animate({
                'padding-bottom': 20
            }, 1200, 'easeOutQuart');
        });
        $('#inside > p:last').css('padding-bottom', 20);


        if ($('#downloads-search').length > 0) {

            $('#downloads-search').unbind();
            $('#downloads-search').bind('keyup keydown change', function () {
                liveMediaSearch();
            });

        }

    }
    $('.overlabel').overlabel();
    $('#section-inside .buttonset').buttonset();
    $('#tweet-bar').animate({
        bottom: 0
    }, 2600, 'easeOutQuart');
    onResizer();
}

function liveMediaSearch() {
    if (window.liveSearchTimer) {
        clearTimeout(window.liveSearchTimer);
    }

    performLiveMediaSearch();
}

function performLiveMediaSearch() {
    window.liveSearchTimer = setTimeout(function () {
        downloadsSearch();
    }, 1000);
}

function initSearch() {
    $('#input-search').autocomplete({
        source: pids.search,
        dataType: 'jsonp',
        minLength: 2,
        select: function (event, ui) {
            $.address.value(ui.item.value);
            $('#input-search').value('');

            return false;
        },
        focus: function (event, ui) {
            $('#input-search').val(ui.item.label);
            return false;
        }
    })
    .data('autocomplete')._renderItem = function (ul, item) {
        return $('<li></li>')
    .data('item.autocomplete', item)
    .append('<a href="javascript:;">' + item.label + '</a>')
    .appendTo(ul);
    };

}

function setInsideHeight() {
    fHeight = $('#inside').height();
    $('#inside').css('height', fHeight);
}

function unsetInsideHeight() {
    $('#inside').css('height', 'auto');
}

function downloadsChangeYear() {
    showLoader();
    setInsideHeight();

    $('#media-widget-container').fadeOut(150);
    fYear = $('#downloads-select-year').val();
    $.getJSON(window.remoteURL + 'media-get-year&linkid=' + fYear, function (json) {
        if (json.status == 'OK') {
            updateDownloadsPage(json);
            $('#downloads-search').val('');
        } else {
            trace(json.message);
        }
        hideLoader();
    });
}

function downloadsSearch() {
    fSearch = $('#downloads-search').val();
    if (parseInt(fSearch.length) > 2) {
        showLoader();
        setInsideHeight();
        $('#media-widget-container').fadeOut(150);
        $.post(window.remoteURL + 'media-search', { 'SEARCH': fSearch }, function (json) {
            if (json.status == 'OK') {
                updateDownloadsPage(json);
            } else {
                trace(json.message);
            }
            hideLoader();
        }, 'json');

    } else if (fSearch.length == 0) {
        downloadsChangeYear();
    }
}

function updateDownloadsPage(json) {
    $('#media-widget-container').html(json.data);
    initCWLAccordions();
    doCufon();
    $('#media-widget-container').fadeIn(150, function () {
        unsetInsideHeight();
    });
}

function initAudio() {
    $("#jquery_jplayer_1").jPlayer({
        ready: function () {
        },
        swfPath: '/net/js/jquery/jPlayer.2.1.0',
        wmode: "window",
        supplied: 'mp3,m4a',
        ended: function() {
            $('div.jp-audio').fadeOut(300);
        }
    });

}


function mediaDownload(fID) {
    location.href = window.remoteURL + 'media-download&linkid=' + fID;
}

function playAudio(fObj, fURL) {
    fName = $(fObj).attr('title');
    fAuthor = $(fObj).attr('author');
    fDate = $(fObj).attr('date');

    if (fAuthor != '') {
        fName += ' by ' + fAuthor;
    }

    if (fDate != '') {
        fName += ' on ' + fDate;
    }

    fType = 'mp3';
    fObj = {
        mp3: fURL,
    };

    if (fURL.indexOf('.m4a') > 1) {
        fType = 'm4a';
        fObj = {
            m4a: fURL
        };
    }
    $("#jp_container_1").unbind();
    $("#jp_container_1").bind('mouseleave', function() {
        window.audioSlider = setTimeout(function() {
            audioPlayerSlideUp();
        }, 1000);
        
    });

    $("#jp_container_1").bind('mouseenter', function() {
        clearTimeout(window.audioSlider);
        audioPlayerSlideDown();
    });

    $("#jquery_jplayer_1").jPlayer();
    $("#jquery_jplayer_1").jPlayer("setMedia", fObj).jPlayer('play');

    $('.jp-title > ul > li').html(fName);
    doCufon();
    audioPlayerSlideDown();

    window.audioSlider = setTimeout(function() {
        audioPlayerSlideUp();
    }, 20000);
}

function audioPlayerSlideDown() {
    $('#jp_container_1').dequeue().animate({
        'top': 0
    }, 750, 'easeOutQuart');
}

function audioPlayerSlideUp() {
    $('#jp_container_1').dequeue().animate({
        'top': -37
    }, 750, 'easeOutQuart');
}

/* Calendar */
function initCalendar() {
    showLoader();

    $('#calendar').fullCalendar({
        height: 200,
        header: {
            left: 'prev,today,next,title',
            center: '',
            right: ''
        },
        viewDisplay: function(fViewObj) {
            // trace($.fullCalendar.formatDate(fViewObj.start, 'M/d/yyyy') + ' > ' + fViewObj.end);
        },
        events: {
            url: window.remoteURL+'event-feed-json'
        },
        loading: function(isLoading, view) {
            if (isLoading) {
                showLoader();
            } else {
                hideLoader();
            }
        },
        eventAfterRender: function(event, element, view) {
            $('.fc-day-number').each(function() {
                fDay = $(this).html();
                $(this).parent().parent().attr({
                    'day': fDay
                });
            });

            $('td[day="'+event.day+'"]').each(function() {
                if ($(this).hasClass('fc-other-month') == false) {
                    $(this).addClass('fc-state-highlight').attr('id', event.id).removeClass('fc-today');
                }
            });
        },
		dayClick: function(date, allDay, jsEvent, view) {
			showEventsForDay(date);
		}
    });
}

function showEventsForDay(fDate) {
	showLoader();
	fURL = window.remoteURL+'event-feed-json-by-day&date='+$.fullCalendar.formatDate(fDate, 'M/d/yyyy')+'&rnum='+getRandomNumber(9999);
	$.getJSON(fURL, function(jsonArray) {
		fData = '';
		for (i=0; i<jsonArray.length; i++) {
			json = jsonArray[i];
			fData += json.html;
		}
		$('#event-items').html(fData);
		hideLoader();
	});
}

function openEvent(fObj) {
    trace(fObj.attr('id'));
}

/* Forms */
function submitForm(fDomID, fFormID) {
    showLoader();
    if (checkForm(fDomID)) {
        fArray = $(fDomID).serializeArray();
        $.post(window.remoteURL + 'submit-form&linkid=' + fFormID, fArray, function (json) {
            if (json.status == 'OK') {
                $('.tab.open .extruder').trigger('click');
                $(fDomID + ' .input-text, ' + fDomID + ' .input-textarea').val('');
                fancyboxDisplay(json.message);
            } else {
                fancyboxDisplay(json.message);
            }
            hideLoader();
        }, 'json');
    } else {
        hideLoader();
    }
}

function checkForm(fDomID) {
    /* Text / TextArea / Select Fields */
    fStatus = true;
    $(fDomID + ' .input-text.input-required, ' + fDomID + ' .input-select.input-required, ' + fDomID + ' .input-textarea.input-required').each(function () {
        fVal = $(this).val();
        if (fVal == '' || fVal == -1) {
            fStatus = false;
            $(this).addClass('input-warning');
        } else {
            $(this).removeClass('input-warning');
        }
    });

    $(fDomID + ' .input-radio.input-required').each(function () {
        fName = $(this).attr('name');
        fLen = $('.input-radio[name="' + fName + '"]:checked').length;
        if (fLen == 0) {
            fStatus = false;
            $('.input-radio[name="' + fName + '"]').parent().addClass('input-warning');
        } else {
            $('.input-radio[name="' + fName + '"]').parent().removeClass('input-warning');
        }
    });

    $(fDomID + ' .input-checkbox.input-required').each(function () {
        fChecked = eval($(this).attr('checked'));
        if (fChecked == false) {
            fStatus = false;
            $(this).parent().addClass('input-warning');
        } else {
            $(this).parent().removeClass('input-warning');
        }
    });


    if (fStatus) {

    } else {
        fMsg = 'Sorry, you missed some fields...';
        fancyboxDisplay(fMsg);
    }

    return fStatus;

}

/* Login */
function loginScreen() {
	location.href='/net/';
	//$('#login-screen').fadeIn(300);
}

function loginScreenClose() {
	$('#login-screen').fadeOut(300);
}

function login() {
	fancyboxDisplay('Sorry, the login function is currently unavailable.<br><br>Please check back later today :)<br><br>- <i>Jason Chin</i>');
}
