// globals
var queryString = '';

function showRequest(formData, jqForm, options) {

    // update latest queryString
    queryString = $.param(formData);

    $('#matrix-results').block({
        message: '<span>Searching Feature List</span>',
        css: { 
            padding:        0, 
            margin:         0, 
            width:          '30%', 
            top:            '10%',
            left:           '35%', 
            textAlign:      'center', 
            color:          '#000', 
            border:         'none', 
            backgroundColor:'#fff', 
            cursor:         'wait' 
        },
        overlayCSS:  { 
            backgroundColor: '#fff',
            opacity:         1
        }
    });

    return true; 
 
} 
 
function showResponse(responseText, statusText)  {

    // clear matrix error
    $('.matrix-error').fadeOut();

    // timeout response until blockUI
    setTimeout ( function(){ $('#matrix-results-inner').html(responseText); }, 500);
    
	$.scrollTo('#matrix-form');

    // unblockUI
    setTimeout ( function(){ $('#matrix-results').unblock({ message: null }); }, 500 );

}

function alertBlock(text) {

    $.blockUI({
        message: text,
        css: { 
            padding:        0, 
            margin:         0, 
            width:          '400px', 
            top:            '40%', 
            left:           '35%', 
            textAlign:      'center', 
            color:          '#000', 
            border:         '3px solid #ccc',
            backgroundImage:'none',
            backgroundColor:'#fff', 
            cursor:         'wait'
        },
        overlayCSS:  { 
            backgroundColor: '#fff',
            opacity:         '0.75'
        },
        timeout: 1000,
        baseZ: 999999
    });

}

function confirmBlock(text) {

    $('#question').children('h2').text(text);
    $.blockUI({ 
        message: $('#question'), 
        css: { 
            padding:        0, 
            margin:         0, 
            width:          '400px', 
            top:            '40%', 
            left:           '35%', 
            textAlign:      'center', 
            color:          '#000', 
            border:         '3px solid #ccc',
            backgroundImage:'none',
            backgroundColor:'#fff', 
            cursor:         'wait'
        },
        overlayCSS:  { 
            backgroundColor: '#fff',
            opacity:         '0.75'
        },
        baseZ: 999999
    });

}

function newURLForm() {

    $.blockUI({ 
        message: $('#new-matrix-form'), 
        css: { 
            padding:        0, 
            margin:         0, 
            height:         '130px',
            width:          '400px', 
            top:            '40%',
            left:           '35%',
            textAlign:      'center',
            color:          '#000',
            border:         '3px solid #ccc',
            backgroundImage:'none',
            backgroundColor:'#fff',
            cursor:         'wait'
        },
        overlayCSS:  { 
            backgroundColor: '#fff',
            opacity:         '0.75'
        },
        baseZ: 999999
    });

}

function emailBlock(text) {

    $.blockUI({ 
        message: $('#email'),
        css: { 
            padding:        0, 
            margin:         0, 
            height:         '200px',
            width:          '400px', 
            top:            '40%', 
            left:           '35%', 
            textAlign:      'center', 
            color:          '#000', 
            border:         '3px solid #ccc',
            backgroundImage:'none',
            backgroundColor:'#fff', 
            cursor:         'wait'
        },
        overlayCSS:  { 
            backgroundColor: '#fff',
            opacity:         '0.75'
        },
        baseZ: 999999
    });

}

//equal widths
function equalWidth(group) {
    widest = 0;
    group.each(function() {
        thisWidth = $(this).width();
        if(thisWidth > widest) {
            widest = thisWidth;
        }
    });
    group.width(widest);
}

$(document).ready(function() {

    /*
    * Verdatum Product Matrix
    * 08.14.2009 TRA
    */
    $('#feature-matrix').css('overflow', 'hidden');
    $('#feature-matrix fieldset:odd').addClass('odd');
    $('#feature-matrix fieldset:first').addClass('current');

    // horizontal scrolling
	$('#feature-matrix-container').serialScroll({
		target:'#feature-matrix',
		items:'fieldset',
		prev:'a.prev',
		next:'a.next',
		axis:'x',
		navigation:'#slide-nav a',
		duration:500,
		force:true,
		cycle:false,
		onBefore:function( e, elem, $pane, $items, pos ){
			e.preventDefault();
			if( this.blur ) {
				this.blur();
            }
            $items.removeClass('current');
            $(elem).addClass('current');

			$('#slide-nav li').removeClass('selected');
			$('#slide-nav li:eq('+pos+')').addClass('selected');

		},
		onAfter:function( elem ){
			//'this' is the element being scrolled ($pane) not jqueryfied
		}
	});

    // set nav selected
    $('#slide-nav li:first').addClass('selected');
    $('#slide-nav a').click(function(){
        $('#slide-nav li').removeClass('selected');
        $(this).parent('li').addClass('selected');
    });


    /*
    *   NyroModal applied to search results links
    */

    $('.feature-link').live("click", function(){
        $('.feature-link').removeClass('selected');
        $(this).addClass('selected');

        $.nyroModalManual({
            url: $(this).attr('href'),
            bgColor: '#ffffff'
        });
        return false;
    });

    // widen page content via class matrix (fix)
    $('#content').addClass('matrix');

    // add form action only after .ready to prevent post before js load
    $('#matrix-form').attr('action', '/_includes/matrix/matrix_view_search.php');

    /*
    *   Ajax form
    */
    var options = {
        //target:        '#matrix-results-inner',
        beforeSubmit:  showRequest,
        success:       showResponse
    };
    // bind form
    $('#matrix-form').ajaxForm(options);

    /*
    *   jQuery MultiSelect and callback
    */
    $('#feature-matrix select').multiSelect(null, function() {
        $('#matrix-form').submit();
    });

    // set common width
    $('#feature-matrix fieldset div.multiSelectOptions').each(function(){
        equalWidth($(this).children('label'));
    });

    /*
    *   Set Width of inner slider
    */
    var outer_width = 0;
    $('#feature-matrix .inner fieldset').each(function(){
        outer_width += $(this).outerWidth();
    });
    $('#feature-matrix .inner').width(outer_width);

    /*
    *   Check for incoming url string last
    */
    if ( jQuery.url.param("s") == '1' ) {
        // submit form
        $('#matrix-form').submit();
        // scroll to content
        $.scrollTo('#main-nav');
    }


    /*
    *   Add new matrix url
    */
    $('a.new-matrix-url').click(function(){
        //$('.new-matrix-form').slideDown();
        newURLForm();
        return false;
    });

    /*
    *   save a current matrix state
    */
    $('input.save-matrix-url').click(function(){
        var uid = $('input#uid').val();
        var url_name = $('input#url-name').val();

        if ( url_name !== '' ) {
            $.post("/_includes/matrix/matrix_view_add.php", { user_id: uid, url_name: url_name, url: queryString },
            function(data){
                $('#url-name').val('').removeClass('error');
                $('.new-matrix-form').slideUp();

                // append to current list rather than refresh
				if ($('#saved-features .sub-menu').length != 0) {
                	$('#saved-features .sub-menu').append('<li><a href="?' + queryString + '">' + url_name + '</a><a href="#" rel="' + data + '" class="delete-url">Delete</a></li>');
                	$.unblockUI(); 
					$.scrollTo('#matrix-form');
				} else {
					location.reload(true);
				}
            });
        } else {
            $('#url-name').addClass('error');
        }
        return false;
    });

    /*
    *   delete a stored url
    */
    $('a.delete-url').live("click", function(){
        var url_id = $(this).attr('rel');
        $(this).addClass('selected');

        confirmBlock('Are you sure you want to delete this saved URL?');

        $('#yes').click(function() {
            $.post("/_includes/matrix/matrix_view_delete.php", { id: $('a.delete-url.selected').attr('rel') },
            function(data){
                $.unblockUI();
                $('a.delete-url.selected').parent('li').remove();
            });
        }); 
    
        $('#no').click(function() { 
            $('a.delete-url').removeClass('selected');
            $.unblockUI(); 
            return false;
        }); 

        return false;
    });

    
    /*
    *   email a matrix url
    */
    $('a.email-url').click(function(){
        var url_id = $(this).attr('rel');

        emailBlock(url_id);

        $('#send-email').live("click", function() {
            var email_to = $('#email-to').val();
            var email_from = $('#email-from').val();
            var email_comments = $('#email-comments').val();
            $.post("/_includes/matrix/matrix_view_email.php", { email_to: email_to, email_from: email_from, email_comments: email_comments, url: queryString },
            function(data){
                $.unblockUI();
            });
            return false;
        });
    
        $('#no-email').click(function() { 
            $('a.delete-url').removeClass('selected');
            $.unblockUI(); 
            return false;
        }); 

        return false;
    });

    // cancel modal and clear input values
    $('.cancel-modal').click(function(){
        $('.blockUI').find('input[type="text"]').val('');
        $.unblockUI();
        return false;
    });

    // cancel my-features click
    $('li.my-features > a').click(function(){
        return false;
    });

	/******
	tooltip
	*******/
	$('#slide-nav li a').each(function () {	
		
		var showDistance = 20;
		var hideDistance = 30;
	    var time = 250;
	    var hideDelay = 70;
	    var hideDelayTimer = null;
	    var beingShown = false;
	    var shown = false;
	    var quote = $('span.hover-quote', this).css('opacity', 0);

	    // set the mouseover and mouseout on both element
	    $(this).parent('li').hover(function () {
			// stops the hide event if we move from the trigger to the quote element
			if (hideDelayTimer) 
				clearTimeout(hideDelayTimer);
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;
				// reset position of quote box
				quote.css({ 
					position: 'absolute', 
					display: 'block'
				}).animate({
					bottom: showDistance,
					opacity: 1
				}, time, 'swing', function() {
					beingShown = false;
					shown = true;
				});
			}
	    },function () {
			// reset the timer if we get fired again - avoids double animations
			if (hideDelayTimer) 
				clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				quote.animate({
					bottom: hideDistance,
					opacity: 0
				}, time, 'swing', function () {
					// once the animate is complete, set the tracker variables
					shown = false;
					quote.css({'display' : 'none', 'bottom' : hideDistance });
				});
			}, hideDelay);
	    });
	});


}); // doc ready