/*
 * © 2010 htmlBlender.com
 * All rights reserved
 * www.htmlBlender.com
 * */

$(document).ready(function(){
    
	//	Perform initialization routines
	initMainMenu();
    initAskQuestion();  
	initNewsletter();
    initNewWindowLinks();
    initInputHints();
    initFadingElements();
    initPreviewTabs();
    initFileCtrls();
    initAccordion();
    
    //	Initialize Online Chat Arrow
    var _cookie = $.cookie;
    setTimeout( function() { initChatOnline(_cookie); } , 2500);
    
    $('#online-support,#online-support-contact,.onlinechat').click(function(){
        window.open('/livesupport/livezilla.php', 'livesupport', 'width=590,height=550,left=0,top=0,resizable=yes,menubar=no,location=no,status=yes,scrollbars=yes');
        return false;
    });
    
    $('#online-support-arrow').click(function(){
        window.open('/livesupport/livezilla.php', 'livesupport', 'width=590,height=550,left=0,top=0,resizable=yes,menubar=no,location=no,status=yes,scrollbars=yes');
        return false;
    });
    
    $('.delete-note').click(function() {
    	return window.confirm('Would you like to delete this comment? Press \'OK\' to continue or \'Cancel\' to close this alert.');
    });
});

//	Initialize main menu items
function initMainMenu()
{
	if($.browser && $.browser.msie && $.browser.version == '6.0'){
		$('#mainmenu LI').hover(function(){
            $(this).children('UL').show();
            $(this).children('DIV').show();
            $(this).children('DIV').children('UL').show();
		}, function(){
		  $(this).children('UL').hide();
		  $(this).children('DIV').hide();
		});
	}
}

//	Initialize 'Ask a Question' forms
function initAskQuestion()
{
    $('#ask-question-form').submit(function(){
		var formData = $(this).serialize();
        //$('#ask-question-form').hide('normal');
        $('#ask-question').addClass('loading');

        var actionUrl = $('#ask-question-form').attr('action');
        $.ajax({
            type: 'POST',
            url: actionUrl,
            data: formData,
            success: function(response, responseStatus){
                $('#ask-question').removeClass('loading');
                
                if(response.substring(0, 6) == 'ERROR:'){
                    //   Display error message
                    response = response.substring(6);
                    $('#ask-question-p').html(response);
                    $('#ask-question-p').css('background-color', '#FFFFCC');
                } else {
                    $('#ask-question-form').html(response);
                    $('#ask-question-form').show('normal');                
                }
            }
        });
        return false;
    });
}

function initNewsletter()
{
    $('#newsletter-form').submit(function(){
		var formData = $(this).serialize();
		$('#newsletter').addClass('loading');

        var actionUrl = $('#newsletter-form').attr('action');
        $.ajax({
            type: 'POST',
            url: actionUrl,
            data: formData,
            success: function(response, responseStatus){
                $('#newsletter').removeClass('loading');
                
                if(response.substring(0, 6) == 'ERROR:'){
                    //   Display error message
                    response = response.substring(6);
                    $('#newsletter-p').html(response);
                    $('#newsletter-p').css('background-color', '#FFFFCC');
                } else {
                    $('#newsletter-form').html(response);
                    $('#newsletter-form').show('normal');                
                }
            }
        });
        return false;
    });
}

//	Live chat initialization
function initChatOnline( _cookie )
{
	
    var cookieVal = _cookie('ignoreChatArrow');
    if(cookieVal >= 3 || !$('#online-support')) { return; }
    
    _cookie('ignoreChatArrow', !cookieVal ? 1 : (parseInt(cookieVal) + 1));
    var osPos = $('#online-support').position();
    $('#chat-online').css('display', 'block');
    $('#chat-online').css('top', -300);
    $('#chat-online').css('left', -200);
    
    $('#chat-online').animate({left: (osPos['left'] - 255), top: (osPos['top'] + 22)}, 2000, 'easeOutBounce');
    setTimeout("$('#chat-online').hide('slow');", 7000);
}

/*  Common Routines  */
function initNewWindowLinks(){
    $("a[rel='new-window']").each(function(i, el){
        $(el).click(function(){
            window.open($(this).attr('href'), '_blank');
            return false;
        });
    });
}

//	Fading elements initialization
function initFadingElements(){
    $('.fading-element').css('opacity', 0.7);
    $('.fading-element').bind('mouseenter', function(){
        $(this).fadeTo('normal', 1);    
    }).bind('mouseleave', function(){
        $(this).fadeTo('normal', 0.7);  
    });
}

//	Initializing hints for input fields
function initInputHints(){
    jQuery.each($('input, textarea'), function(i, el) {
        $(el).focus(function(){ if($(this).val() == $(this).attr('title')){ $(this).val(''); } });
        $(el).blur(function(){ if($(this).val() == ''){ $(this).val($(this).attr('title')); } });
    });
}

//	Add a bookmark
function Bookmark(url, title){
    if(window.sidebar) {
        window.sidebar.addPanel(title, url, '');
    } else if(document.all){
        window.external.AddFavorite(url, title);
    }
}

//	Tabs for samples page
function initPreviewTabs() {
    jQuery.each($('.preview-tabs a'), function(i, el) {
        $(el).click(function(){
            $('#' + $('.preview-tabs a.active').attr('rel')).hide();
            $('.preview-tabs a.active').removeClass('active');
            $(this).addClass('active');
            $('#' + $(this).attr('rel')).show();
        });
    });
}

/*  Order Page  */
function initOrderOptions(){

    if(!$('input#addPrices').attr('value')){ return; } // No elements - no job
    
    $('#options').attr('href', 'javascript:;');
    $('.additional-options .frame').hide('slow');
    
    $('#options').bind('click', function (){
        if($(this).attr('state') && $(this).attr('state') == 1){
            $(this).text('(show)');
            $(this).attr('state', 0);
            $('.additional-options .frame').hide('slow');
        } else {
            $(this).text('(hide)');
            $(this).attr('state', 1);
            $('.additional-options .frame').show('slow');
            $.scrollTo($('#options'), 1000, {over:{top:0.1, left:-0.5}});
        }
    });
    
    jQuery.each($('.package'), function(i, el) { 
        $(el).bind('click', function(){
            jQuery.each($('.package'), function(i, el) { $(el).removeClass('active'); });
            $(this).find('input')[0].click();
            $(this).addClass('active');
            var package = $($(this).find('input')[0]).attr('value');
            
            jQuery.each($('.additional-options input, .additional-options label'), function(i, el) {
                if(($(el).attr('id') && $(el).attr('id').split('_')[2] != package) || ($(el).attr('for') && $(el).attr('for').split('_')[2] != package)){ 
                    $(el).addClass('hidden'); 
                } else { 
                    $(el).removeClass('hidden');
                }
            });
        });
    });
    
    jQuery.each($('.orders input[type="radio"]'), function(i, el) { $(el).bind('click', CalculateTotalPrice); });
    
    jQuery.each($('#addPrices').attr('value').split(','), function(i, el) { $('#' + el.split('|')[0]).attr('price', el.split('|')[1]); });
    
    $('#inum-pages').bind('keyup', CalculateTotalPrice);
    
    $('#addPrices').attr('value', '');
}

function CalculateTotalPrice(){
    var sum = 0;
    jQuery.each($('.orders input[type="radio"]'), function(i, el) { 
        if($(el).attr('checked') == true && $(el).attr('price') && IsActivePackage($(el).attr('name'))){ sum += parseInt($(el).attr('price')); }
    });
    
    if(!parseInt($('#inum-pages').val('value')) || $('#inum-pages').attr('value') < 0) { $('#inum-pages').attr('value', 1); }
    sum *= parseInt($('#inum-pages').attr('value'));
    
    $('#total-price').text(sum.toFixed(2));
}

function IsActivePackage(name){
    var package = 0;
    
    if(name.toLowerCase() == 'package') { return true; }
    
    jQuery.each($('.orders input[name="package"]'), function(i, el) { 
        if($(el).attr('type').toLowerCase() == 'radio' && $(el).attr('checked') == true){ package = $(el).attr('value'); }
    });
    
    return (parseInt(name.split('_')[2]) == package);
}

function DisplayError( message ) {
    $('#error-msg').text(message);
    $('#error-msg').show('slow');
}

function load( url ) { window.location.href = url; }

function initFileCtrls() {
	if($('#add-file').length > 0) {
		$.file_cnt = 0;
		$('#add-file').click(function() {
			if($.file_cnt < 4) {
				var elem = $('<div class="row"><a href="#" class="remove">Remove</a><input type="file" name="files[]" /></div>').appendTo('.files-container');
				$(elem).find('a.remove').click(function() {
					$.file_cnt--;
					$(this).parent().remove();
					if($.file_cnt < 4) {
						$('#add-file').show();		
					}
					return false;
				});
				$.file_cnt++;
			}
			if($.file_cnt >= 4) {
				$(this).hide();
			}
		});
	}

	if($('#add-url').length > 0) {
		$.url_cnt = 0;
		$('#add-url').click(function() {
			if($.url_cnt < 4) {
				var elem = $('<div class="row"><a href="#" class="remove">Remove</a><input type="text" name="urls[]" value="" /></div>').appendTo('.urls-container');
				$(elem).find('a.remove').click(function() {
					$.url_cnt--;
					$(this).parent().remove();
					if($.url_cnt < 4) {
						$('#add-url').show();		
					}
					return false;
				});
				$.url_cnt++;
			}
			if($.url_cnt >= 4) {
				$(this).hide();
			}
		});
	}
}

function initAccordion()
{
	if($('DL.accordion').length < 1){ return; }
	$('DL.accordion DT').click(function(){
		if($(this).parent().hasClass('only-1-can-expand')){
			if(!$(this).hasClass('expanded')){
				$('DL.accordion DT.expanded').each(function(){ accordionToggleSection($(this)); });
			}
		}
		
		accordionToggleSection($(this));
	});
}

function accordionToggleSection(sectionObj)
{
	sectionObj.toggleClass('expanded');
	if(sectionObj.hasClass('expanded')){
		sectionObj.next().slideDown('fast', function(){ $(this).addClass('visible'); });
	} else {
		sectionObj.next().slideUp('fast', function(){ $(this).removeClass('visible'); });
	}
}
