/**
 * CoffeeCup Software's Empire: Main Javascript Library
 *
 * This file contains main javascript library for the
 * empire application.
 *
 * @author     Jeff Welch <jw@coffeecup.com>
 * @category   Empire
 * @package    Public
 * @copyright  Copyright (c) 2006-2012 CoffeeCup Software, Inc. (http://www.coffeecup.com/)
 * @version    $Id$
 */

$(document).ready(function() {
    // Makes external anchor tags open links in new windows
    $('a:not(.colorbox):not(.colorbox_iframe):not(.colorbox_flash):not(.stay)[href^="http://"]')
       .not('[href*="' + document.domain + '"]').not('[href*="recaptcha.net"]').addClass('external');
    $('a.external').click(function() { window.open(this.href); return false; });

    // Login links open in new windows
    $('a.login').click(function(){ window.open(this.href); return false; });

    // Logout link should submit logout form so that logout uses POST and isn't open to CSRF
    $('a.logout_link').click(function(){ $('#logout_form').submit(); return false; });

    // Allow for toggling billing address on and off
    if($('input#toggle_billing').attr('checked')){$('fieldset#shipping_address_info').hide()}
    $('input#toggle_billing').click(function(){$('fieldset#shipping_address_info').slideToggle('fast')});

    // Setup the list sorters
    if($.fn.ccListSorter){$('ul.sortable').ccListSorter();}
    // Setup the syncers
    if($.fn.ccSync){$('input#sync').ccSync();}
    // Setup the long uploads
    if($.fn.ccLongUpload){$('input.long_upload').ccLongUpload();}
    // Setup the waiting processor
     if($.fn.ccLongProcess){$('input.long_process').ccLongProcess();}
    // Setup slug builder
    if($.fn.ccSlugBuilder){$('form.slug_builder').ccSlugBuilder();}
    // Setup tag selector
    if($.fn.ccTagSelector){$('form.tag_selector').ccTagSelector();}
    // Setup star rater
    if($.fn.rating){$('input[type=radio].star').rating();}
    // Setup formsaver
    if($.fn.ccFormSaver){$('form.formsaver').ccFormSaver();}
    // Setup Slider
    if($.fn.ccSlider){$('#bundle_scroller').ccSlider();}
    // Setup ckeditor
    if($.fn.ckeditor) {
       $('.ckeditor_simple').ckeditor({toolbar: 'Simple'});

       CKEDITOR.on( 'instanceReady', function( ev ) {
         var dtd = CKEDITOR.dtd;

         for (var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent)) {
            ev.editor.dataProcessor.writer.setRules( e, {
               breakAfterOpen : false
            });
         }
       });
    }

    $('#bundle_scroller .bundle').addClass('active').click(function() {
       location.href = $(this).find('p a').attr('href');
    });

    $('#header_search #search_button').val('');
    $('#quickcheckout #sign_in_button').val('');
    $('#search_field').focus(function(){
       if($(this).val() == 'Search…') {
          $(this).val('');
       }
    }).blur(function(){
       if($(this).val() == '') {
          $(this).val('Search…');
       }
    });

    if($('#hide_smilies :checkbox:checked').length){$('.smiley').hide()}
    $('#hide_smilies :checkbox').click(function(){
       $('.smiley').toggle();
    });

    //fancy trial download email box
    if($('input#trial_download_email'))
    {
       $('input#trial_download_email').focus(function(){if($('input#trial_download_email').val() == 'you@domain.com') $('input#trial_download_email').val('');});
       $('input#trial_download_email').blur(function(){if($('input#trial_download_email').val() == '') $('input#trial_download_email').val('you@domain.com');});
    }

   // opens a form to create an account after downloading a trial version of software
   $('a.subscribe_on_download').click(function(event){
      $.fn.colorbox({href:'/email/from_download/', width:"700px", height:"400px", opacity:"0.5", iframe:true});
   });

   if(parent.jQuery.fn.colorbox) {
      // opens certain links inside the post download colorbox form in the parent window
      $('a.to_parent').click(function(event){
         event.preventDefault();
         parent.location.href = $(this).attr('href');
      });

      $('a.colorbox_closeme').click(function(event){
         event.preventDefault();
         parent.jQuery.fn.colorbox.close();
      });

      //--> for closing the store preview pages from within themselves
      $('<img src="/images/close-window.med.png" width="160" height="30" alt="Close Window" />').appendTo('#store_preview #short_description').click(function(event){
        event.preventDefault();
        parent.jQuery.fn.colorbox.close();
      });
   }


   // closes form message and form error boxes
   $(".form_message #dismiss_message").click(function(event){
      event.preventDefault();
      $('.form_message').fadeOut();
   });
   $(".form_error #dismiss_message").click(function(event){
      event.preventDefault();
      $('.form_error').fadeOut();
   });

    // hide disclaimer notes by default
    $('#disclaimer').hide();
    $('.form_note a[href="#disclaimer"]').click(function(){
       $('#disclaimer').toggle();
       return false;
    });

    $('#contactUs select').change(function(){
       $(this).find('option:selected').each(function () {
          if($(this).val() == '3')
          {
             $('#contact_message').hide();
             $('#button_sendmymessage').hide();
             $('#user_info').hide();
             $('#support_details').show('fast');
          }
          else
          {
             $('#support_details').hide();
             $('#contact_message').show('normal');
             $('#user_info').show();
             $('#button_sendmymessage').show();
          }
      }).change()
    });

    // Open max-width'ed images in colorbox
    $('div.postcontents img').each(function(){

       if($.browser.msie && parseInt($.browser.version) <= 6 && $(this).width() > 505)
       {
          $(this).css('width','505px');
       }

       if($(this).width() == '505')
       {
          $(this).wrap('<a class="expandable_image colorbox" href="' + $(this).attr('src') + '"></a>');
       }
    });

    // hides the text 'add to cart' on software product home pages
    if($('.primary #addbutton')) {
       $('ul.primary #addbutton').attr("value","");
    }

    $('#product_price').css({'cursor':'pointer'}).click(function(){
       $('#add_to_cart').click();
    });

    // for toggling FAQ's on /contact/
    $('#faqnotice').append("<br /><br /><b id=\"faqtoggle\">Save some time &mdash; Check out the FAQ</b>");
    $('#contactfaqs').hide();
    $('#contactfaqs p').hide();
    $('#faqtoggle').click(function() {
       $('#contactfaqs').slideToggle('slow');
    });
    $('#contactfaqs b').click(function() {
       $(this).parent().find('p').toggle();
       $(this).css({color:"#333", textDecoration:"none"})
    });

    $('.ccui_message .close').click(function(event){
       event.preventDefault();
       $(this).parents('.ccui_message').fadeOut('slow');
    });

   function initializeColorbox(){
      if($.fn.colorbox){
          if($('.colorbox_option').length > 0)
          {
             $('.colorbox_option').each(function(){

                var rel = $(this).attr('rel');
                if(rel) {
                   rel=' rel="' + rel + '" ';
                }

                $(this).before('<a title="' + $(this).attr('title') + '"' + rel + ' class="colorbox_iframe_added" href="' + $(this).attr('href') + '?colorbox_preview=true"><img src="/images/icons/page_white_magnify.png" /></a>');
             });
          }
          $("a.colorbox").colorbox({width:"75%", height:"75%"});
          $("a.cbox_screenshot").colorbox({width:"80%", height:"80%"});
          $("a.colorbox_iframe, a.colorbox_iframe_added").colorbox({width:"75%", height:"75%", iframe:true});
          $("a.store_preview").colorbox({  width:"90%", height:"90%", maxWidth:"900px", maxHeight:"610px", opacity:"0.5", iframe:true});
          $("a.colorbox_flash").colorbox({width:'700px', height:'470px'});
      }

      if($.fn.actionModal){
          $("a.action_modal").actionModal({innerWidth:"700px", height:"500px", iframe:true, scrolling:false});
      }
   }
   initializeColorbox();


    $.defaultText = {
        settings: {
            message_class: 'description_text',
            message: 'Your text goes here'
        }
    }
    $.fn.extend({
        defaultText: function(settings) {
            var settings = $.extend({}, $.defaultText.settings, settings);
            $(this).each(function(){
                var input = $(this);
                input.focus(function(){
                    if(input.val() == settings.message) {
                        input.val('').removeClass(settings.message_class);
                    }
                }).blur(function(){
                    if(input.val() == '') {
                        input.val(settings.message);
                    }
                    if(input.val() == settings.message) {
                        input.addClass(settings.message_class);
                    }
                }).blur().closest('form').submit(function(){
                    if(input.val() == settings.message) {
                        input.val('').removeClass(settings.message_class);
                    }
                });
            });
            return $(this);
        }
    });

    $('#first_name,#last_name').defaultText({message:'(as appears on your card)'});
    $('#address_info .column1 input, #address_info .column2 input,' +
      '#address_info .column1 select, #address_info .column2 select').focus(function(){
       $('#default_address_new').click();
    });

   // Setup the global checkbox
   if($('#global_check').length)
   {
      $('#global_check').change(function(){
         var global_checked = this.checked;
         $('td.check input[type=checkbox]').each(function(){
            this.checked = global_checked;
            $(this).change();
         });
      });

      $('td.check input[type=checkbox]').change(function(){
         if(!this.checked)
         {
            $('#global_check').attr('checked','');
         }
      });
   }

    $('#payment_methods tr').click(function(){
       $(this).find('.payment_option input').click();
    });

    /* S-Drive URL Thingy */
    if($("#sdrive-slug").length)
    {
      jQuery.ccGetSdriveSlug = function(slug) {
         return slug ? slug.toLowerCase().replace(/\s/g,'-').replace(/[^a-z0-9-]/g,'').replace(/^-+|-+$/g, '') : '';
      }

      $("#sdrive-slug").defaultText({message:'yournamehere'}).bind('keyup change blur update', function(e){
         $("em.user_slug").text($.ccGetSdriveSlug($(this).val()) || 'yournamehere');
      }).change().parents('form').submit(function(event){
         var user_slug_text = $("em.user_slug:first").text();
         if (user_slug_text == 'yournamehere') {
            user_slug_text = '';
         }

         $("#sdrive-slug").val(user_slug_text);
         $(this).unbind(event);
      });
    }

    // Hides people in online lists
    if($('#online_list a').length > 10) {
       $('#online_list a:gt(10), #online_list br:gt(10)').hide();
       $('<a href="">View All...</a>').appendTo($('#online_list')).click(function(event){
          event.preventDefault();
          $('#online_list a:gt(10), #online_list br:gt(10)').show();
          $(this).hide();
       });
    }

   // scrolls to an anchor by id on the page
   $('a[id^="goto-"]').click(function(event){
     event.preventDefault();
     var id = $(this).attr("id").substring(5);
     $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
   });

   // handles the NPS form via AJAX
   $('form#nps_form').submit(function(event){
      event.preventDefault();
      $('#nps_source').after('<input type="hidden" name="ajax" value="true">');
      $.post(
         $(this).attr('action'),
         $(this).serialize()
      );
      $(this).fadeOut(400,function(){ $('#nps_thanks').show(); });
   })

});
