Cufon.replace('h1, h2, .header ul li a, .apps li .app_header, .collapsible_list li .app_header, .page_banner .description_header, .cufon');
Cufon.replace('.btn_plain span, .btn_dark span, .page_buttons a span');
//elements that require hover states
Cufon.replace('.flash_wrapper a span, .promotions li a', {
    hover: true
});
//elements that require a text shadow
Cufon.replace('.page_banner .description_header',{
    textShadow: '#333 1px 1px'
});

function init_app(app){
    
    var app_header=app.find('.app_header');
    
    app_header.click(function(){
    
        if($(this).parent().find('.app_content').is(':visible')){
            if(!$(this).parent().hasClass('first_app')) {
                $(this).parent().find('.app_content').slideUp();
                $('.first_app .app_content').slideDown();
                $('.first_app').toggleClass('open');
                $(this).parent().toggleClass('open');
            }
        } else {
            $(this).parent().find('.app_content').slideDown();
            $('.apps .open .app_content').slideUp();
            $('.apps .open').toggleClass('open');
            $(this).parent().toggleClass('open');
        }
    });    
}

function form_select_subject(toggler, input_value, special_value) {

       
       var id=toggler.attr('id');
       
       if(input_value==special_value) {
           $('.'+id+'_default').css('display', 'none');
           $('.'+id+'_special').css('display', 'block');
           
       }
       else {
           $('.'+id+'_default').css('display', 'block');
           $('.'+id+'_special').css('display', 'none');
       }    
       


       return(true);
}

function form_init_select_subject(toggler, special_value) {

      var default_value;

      default_value=toggler.val();
      
      toggler.change(function(){
            form_select_subject(toggler, $(this).val(), special_value);
      });

      form_select_subject(toggler, default_value, special_value);
}

function url_strip_scheme(url) {
         if (url.indexOf("https://") == 0)
             url=url.substring(8); 
    
         if (url.indexOf("http://") == 0)
             url=url.substring(7);
         
         if (url.indexOf("www.") == 0)
             url=url.substring(4);
         
         return(url);

}    
   
$(document).ready(function() {
    
    $('a.promo').hover(function(){  Cufon.refresh(); });
    $('a.promo').mouseout(function(){ 
        var t=setTimeout("Cufon.refresh()",10);
    
    });
    
    
    $('.apps').css('height', $('.apps').height()+5);
    //use js for dropdown nav as not all versions of IE support :hover pseudo class
    if($.browser.msie) {
        $('.header ul li').each(function() {
            $(this).mouseover(function() {
                $(this).find('ul').toggleClass('pseudo_hover');
            }).mouseout(function() {
                $(this).find('ul').toggleClass('pseudo_hover');
            });
        });
    }

    //animation for sliding apps
    $('.apps .app').each(function(){
        
        init_app($(this));
        
    });

    //animation for the showcase
    $('.options li').click(function(){
        $(this).find('a.inline-overlay').trigger('click');
    });
    $('.showcase .options li').click(function(ev) {
        ev.preventDefault();
        if($(this).parent('ul').hasClass('no-tabs')) {
            return false;
        }
        $(this).parent().find('li').removeClass('selected');
        $(this).parents('li').find('.information li').removeClass('selected');

        $(this).addClass('selected');
        $(this).parents('li').find('.information #'+$(this).attr('id').replace('_','')).addClass('selected');
    });

    $('.expandable .expandable_item ul .item_content').not('.visible').hide();
    $('.item_content iframe').hide();
    //animation for the services and contact us pages
    $('.expand_link,.template_link').click(function(ev) {
        ev.preventDefault();

        if($(this).parents('#expandable_item').find('.item_content').is(':visible')){
            $(this).html('Expand');
            $(this).toggleClass('selected');
            $(this).parents('#expandable_item').find('.item_content').slideUp();
        } else {
            $(this).html('Close');
            $(this).toggleClass('selected');
            $(this).parents('#expandable_item').find('.item_content').slideDown();
            map_src = $(this).parents('#expandable_item').find('.item_content iframe').not(':visable').attr('lowsrc');
            var iframes=$(this).parents('#expandable_item').find('.item_content iframe');
            
            if(iframes.length) {
                iframes.not(':visable').attr('src',map_src).fadeIn(500);
            }
        }
    });
    
    //animation for the knowledge base questions
    $('.question_link').click(function(ev) {
        ev.preventDefault();

        if($(this).parents('#expandable_item').find('.item_content').is(':visible')){
            $(this).toggleClass('selected');
            $(this).parents('#expandable_item').find('.item_content').slideUp();
        } else {
            $(this).toggleClass('selected');
            $(this).parents('#expandable_item').find('.item_content').slideDown();
        }
    });

    $('#poll_vote').click(function(){
        
        if($('form#poll_form .radio:checked').length==0) { 
            alert('Please select an poll option');
            return(false);
        }
        
        $.ajax({
            type: 'POST',
            url: '/poll/vote_on_poll',
            data: $('form#poll_form').serialize(),
            success: function(data) {
                $('#poll_form').hide();
                
                $('#poll').html('<div id="results"><div class="app_body">'+ data + '</div></div>');
            }
        });
        return false;
    });
    $('a#poll_results').click(function(){
        $.ajax({
            type: 'GET',
            url: '/poll/results',
            data: $('form#poll_form').serialize(),
            success: function(data) {
                $('#poll_form').hide();

                $('#poll').append('<div id="results"><div class="app_body">'+ data + '</div><div class="app_controls"><a href="#" id="poll_back" class="btn_grey"><span>Back</span></a></div></div>');
                $('#poll a#poll_back').click(function(){
                    $('#poll #results').remove();
                    $('#poll_form').show();
 
                    return false;
                });
            }
        });
        return false;
    });
    //$('#newsletter').prepend('<div class="message"></div>');
    $('#newsletter_submit').click(function() {
        
        submit_val = $(this).attr("data-id");
        
        $.ajax({
            type:'POST',
            url:'/newsletter',
            data: $(this).parents('form').serialize() + '&submit='+ submit_val,
            dataType:'json',
            success: function(data) {
                if(data['status'] == true) {
                    action = submit_val == 'subscribe' ? 'subscribed to' : 'unsubscribed from';
                    message = '<p class="success"><strong>You are now ' + action +' our newsletter.</strong></p>';
                    $('#newsletter .message').html(message);
                }
                else {
                    $('#newsletter .message').html('<p class="error"><strong>'+data['error']+'.</strong></p>');
                }
            }
        });
        return false;
    });
    $('.contact_form .spam_filter').hide();
    $('.spam_filter_hidden #we_will_call_you').submit(function(){
        $('.contact_form .spam_filter').slideDown(500);
        $('.contact_form').removeClass('spam_filter_hidden');
        $('.contact_form').addClass('spam_filter_visible');
        
        $('.spam_filter_visible #we_will_call_you').submit(function(ev) {
            ev.preventDefault();
            $('.contact_form_message').html('<p>Please wait, submitting your details.</p>').fadeIn(500);
            $.ajax({
                data:   $(this).serialize(),
                dataType:'json',
                url:    '/contact/we_will_call_you/json',
                type: 'POST',
                success: function (data){
                    if(data['status'] == true) {
                        $('#we_will_call_you').slideUp(750);
                        $('.contact_form_message').html('</p>Your details have been submitted. We will be in touch shortly.</p>');
                    }
                    else if(data['status'] == false){
                        $('.contact_form_message').html('<p>There was a problem submitting your details.</p>'+data['errors']);
                    }
                    return false;
                }
            });
            return false;
        });



        return false;
    });



    $("a.inline-overlay").fancybox({
        'hideOnContentClick':false,
        'autoDimentions':true,
        'autoScale':false
    });

    $("a.product-overlay").fancybox({
        'hideOnContentClick':false,
        'autoDimentions':true,
        'autoScale':false,
        //'scrolling':'no',
        'height':560,
        'width':850,
        'showNavArrows':false
    });

    $("a.product_order_lnk").click(function(){
        var selected_stock_id=$("#stock_option_selected");

        if($('.stock_option_item').length) {

            var selected_stock_params=$('#stock_option_item_'+selected_stock_id.val()).find('input[name=stock_option_param]').val();

            if($('#stock_option_item_'+selected_stock_id.val()).find('.precustom_radio').length) {

                selected_stock_params+='&FilterFoldCatalog='+$('#stock_option_item_'+selected_stock_id.val()).find('.precustom_radio:checked').val();
            }


            $("#stock_option_selected_params").val(selected_stock_params);

            $("#login_popup_form input[name='stock_option']").val(selected_stock_params);

        }
        
    });
    
    $("a.fancybox").fancybox();

    $('#product_enquiry_form form').submit(function(ev) {
        ev.preventDefault();
        id = $(this).parent('.product_enquiry_form').attr('id');
        $('#product_enquiry_form .messgae').html('<p>Your details are being submitted, please wait.</p>');
        $.ajax({
            data: $(this).serialize()+'&submit=submit',
            dataType:'json',
            url: $(this).attr('action')+'/json',
            type: 'POST',
            success: function (data){
                if(data['status'] == true) {
                    $('#product_enquiry_form .message').html('<p>Your details have been submitted. We will be in touch shortly.</p>');
                    $('#product_enquiry_form form').hide();
                    
                } else if(data['status'] == false) {
                    $('#product_enquiry_form .message').html('<ul>'+data['errors']+'</ul>');
                    
                }
            }
        });
        return false;
    });
    
    $('.product_purchase_form form').submit(function(ev) {
        ev.preventDefault();
        id = $(this).parent('.product_purchase_form').attr('id');
        $('#'+id+' .message').html('<p>Submitting details, please wait.</p>');
        $.ajax({
            data: $(this).serialize()+'&submit=submit',
            dataType:'json',
            url: '/catalogue/login/json',
            type: 'POST',
            success: function (data){
                if(data['status'] == true) {
                    $('#'+id+' .message').html('<p>Beginning order process, please wait.</p>');
                    //GA cross domain tracking
                    _gaq.push(['_link', url_strip_scheme(data['redirect'])]);
                    document.location=data['redirect'];

                } else if(data['status'] == false) {
                    $('#'+id+' .message').html(data['errors']);

                }
            }
        });
        return false;
    });
	
	
	$('#login_controls .login').click( function() {
		
		$('#my_whirlwind_login_popup_form').submit();
		
	});
	
	
	$('#my_whirlwind_login_popup form').submit( function() {
		
		$.ajax({
            data: $(this).serialize()+'&submit=submit',
            dataType:'json',
            url: '/printiq/login_user',
            type: 'POST',
            success: function (data){
                if(data['status'] == true) {
                    if(data['redirect']) {
                        //GA cross domain tracking
                        _gaq.push(['_link', url_strip_scheme(data['redirect'])]);
                        document.location.href=data['redirect'];
                    }

                } else if(data['status'] == false) {
                	var errors = data['errors'];
                	
                	errors = errors.replace(/<p>/g, '');
                	errors = errors.replace(/<\/p>/g, "");
                	
                    alert(errors);

                }
            }
        });
        return false;
		
	});
	
    $('#order_my_print form, #login_popup_form form').submit(function(ev) {
        ev.preventDefault();

    	var message = $(this).parent().find('.message');

    	message.html('<h2>Submitting details, please wait.</h2>');
    
        $.ajax({
            data: $(this).serialize()+'&submit=submit',
            dataType:'json',
            url: '/printiq/login_user',
            type: 'POST',
            success: function (data){
                if(data['status'] == true) {
                    if(data['redirect']) {
                        message.html('<h2>Beginning order process, please wait.</h2>');
                        //GA cross domain tracking
                        _gaq.push(['_link', url_strip_scheme(data['redirect'])]);
                        document.location=data['redirect'];
                    }
                    else {
                        
                        if($('#user_login_panel').length) {
                            $('#user_login_panel').load('/home/get_logged_in_form/homepage', function(){
                                 Cufon.replace('#user_login_panel h1, #user_login_panel h2, #user_login_panel a span'); 
                            });
    
                        }
                        else if($('#apps_login_panel').length) {
                            $('#apps_login_panel').load('/home/get_logged_in_form/apps', function(){
                                 Cufon.replace('#apps_login_panel .app_header, #apps_login_panel h2, #apps_login_panel a span'); 
                                 init_app($('#apps_login_panel'));
                            });

                        }
                        else{
                            document.location.reload(true);
                        }
                    }

                } else if(data['status'] == false) {
                	
                    message.html('<p class="error">'+data['errors']+'</p>');

                }
            }
        });
        return false;
    });

    $('.product_order_lnk').not('.fancybox').click(function(){

        var final_url = $(this).attr('href');
        
        var params=$('#stock_option_selected_params').val();
		
        if(params.length) {
            final_url+=params;
        }
        
        //GA cross domain tracking
        _gaq.push(['_link', url_strip_scheme(final_url)]);

        window.location.href = final_url;

        return false;

    });

    //custom radiobutton styling
    $('.precustom_radio').each(function() {
            $(this).wrap(($(this).is(':checked') ? '<div class="custom_radio selected" ></div>' : '<div class="custom_radio" ></div>'));
    });

    $('.custom_radio input[type=radio]').click(function () {
		$('.precustom_radio[name='+$(this).attr('name')+']').parent('.custom_radio').removeClass('selected');
		$(this).parent().toggleClass('selected');
    });

    $('.stock_options_list .custom_radio input[type=radio]').click(function () {
		$(this).parents('ul.stock_options_list').find('li').toggleClass('selected', false);
                $(this).parents('li').toggleClass('selected', true);
    });

    //custom checkbox styling
    $('.precustom_checkbox').each(function() {

            
            if($(this).is(':checked')){
                    $(this).wrap('<div class="custom_checkbox selected" />');
            } else {
                    $(this).wrap('<div class="custom_checkbox" />');
            }
    });

    $('.custom_checkbox').click(function () {
            $(this).toggleClass('selected');
            
           $(this).find('input').attr('checked', $(this).hasClass('selected'));
    });

    if(jQuery().fancybox) {
      //add in lightboxes
      $("a.iframe").fancybox({autoDimensions: true, scrolling: 'no'});
    }

    $('.toggle').toggleVal();
    $('.toggle_label').toggleVal({
        populateFrom: "label",
        removeLabels: true
    });
  

    var col_max_height = 6; //Max Items per column
    var col_width = 170; //Pixels
    var col_height = 33; //Pixels


    $('.header ul li ul').each(function() {
        var item_count=$(this).find('li').length;

        //no need to split short menus
        if(item_count<=col_max_height) return;

        var split=parseInt(item_count/2);
        split+=item_count%2;

        $(this).find('li').each(function(index){
            column = parseInt(index/split);
            $(this).css('margin-left', column * col_width + 'px')
            if(column > 0) {
                $(this).css('margin-top', (split - (index - (split * column)))* -col_height + 'px').addClass('col_'+column);
            }
        });
    });
    
    
    
    $('#my_whirlwind_login_btn').click( function() {
    	
    	$('#my_whirlwind_login_popup').slideDown();
    	
    });
    
    $('#my_whirlwind_login_popup .close').click(function() {
    	
    	$('#my_whirlwind_login_popup').slideUp();
    	
    });
    

    form_init_select_subject($('#subject_selector'), '6');
    
    form_init_select_subject($('#feedback_subject_type'), 'Other');

});

