var BASE_URL = window.location.protocol + "//" + window.location.host;

function submitTryIt(subscriptionRequired) {
    var serializedForm = $('try_mango_form').serialize(true);

	if (subscriptionRequired) {
		if (serializedForm.course_id.length > 4) {
			$('try_mango_language_error').update('Please select a language to try.');
			$('try_mango_success').hide();
			$('try_mango_language_error').appear();
		} else if (!serializedForm.email && !serializedForm.subscribe) {
			popupClient('/try-it.php');
		} else if (!serializedForm.email && serializedForm.subscribe) {
			$('try_mango_error').update('Please enter a valid email address.');
			$('try_mango_success').hide();
			$('try_mango_error').appear();
		} else {
			subscribeToMailchimp(serializedForm, subscriptionRequiredCallback);
			popupClient('/try-it.php');
		}
	} else {
		if (serializedForm.email) {
			subscribeToMailchimp(serializedForm, function() {});
		}
		popupClient('/try-it.php');
	}
}

function subscribeToMailchimp(serializedForm, ajaxCallback) {
	if (serializedForm.subscribe) {
		new Ajax.Request('/store/mailchimp/subscriber/new/', {
			method:'post',
			onSuccess: ajaxCallback,
			parameters: serializedForm
		}); 
	}
}

function subscriptionRequiredCallback(returnedAJAXObject, json) {
	if (json.success == true) {
		$('try_mango_success').update(json.message);
		$('try_mango_error').hide();
		$('try_mango_success').appear();
		popupClient('/try-it.php');
	} else {
		if(json.message != 'Sorry, but your can not subscribe email adress assigned to another user.'){
			$('try_mango_error').update(json.message);
			$('try_mango_success').hide();
			$('try_mango_error').appear();
		} else {
			$('try_mango_success').update('Welcome Back! Enjoy Mango!');
			$('try_mango_error').hide();
			$('try_mango_subscribe_error').hide();
			$('try_mango_success').appear();
		}
	}
}

function popupClient(b,a){
    var mangoForm = document.getElementById('try_mango_form');
    if(mangoForm) {
        var courseId = '?course_id=' + mangoForm.course_id.options[mangoForm.course_id.selectedIndex].value; 
        if(!(parseInt(a, 10)>0)){a=700;}; 
        var c=window.open(b.replace("****","http") + courseId,"clientWindow","height="+a+",width=1000,toolbar=no,menubar=no,resizable=yes,scrollbars=no,location=no");
        if(c && c.focus){
            c.focus();
        }
    }
}

jQuery(document).ready(function($j) {
    // Add language class to body
    $j('body').addClass( 'lang-' + $j('html').attr('lang') );

    // Search
    if($j('#s').length > 0) {
        $j('#s').attr('value','Search');
    }

    $j('#newsletter_email, #search, #s').focus(function() {
        var $this = $j(this);
        if($this.attr('value') == 'Email Address' || $this.attr('value') == 'Search') {
            $this.attr('value','');
        }
    });

    $j("label#email_error").hide();
    $j('.btn-newsletter').click(function() {
        var email = jQuery("input#newsletter_email").val();
        var patt1 = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (email.match(patt1)) {
            jQuery.ajax({
                  type: "POST",
                  data: 'email=' + email,
                  success: function() {
                    jQuery('#contact_form').html("<div id='message'></div>");
                    jQuery('#message').html("<label for='newsletter_email'>Newsletter</label><h2>Newsletter Subscription Completed!</h2>")
                    .fadeIn(1500, function() {
                      jQuery('#message');
                    });
                  }
                });
            return false;
        } else {
            jQuery("label#email_error").show();
            jQuery("input#email").focus();
            return false;
        }
    });

    $j('#newsletter_email, #search, #s').blur(function() {
        var $this = $j(this);
        if($this.attr('value').length == 0) {
            if($this.attr('id') == 'newsletter_email') { $this.attr('value','Email Address'); }
            if($this.attr('id') == 'search' || $this.attr('id') == 's') { $this.attr('value','Search'); }
        }
    });

    // Make current link active
    var curUrl = window.location;
    $j('li.level1 a, li.about-nav a').each(function() {
        var href = $j(this).attr('href');
        if(href == curUrl) {
            $j(this).addClass('current');
            if($j(this).parents('.about-nav')) {
                $j(this).parent('li').addClass('current');
            }
        }
    });
    
    $$('a[rel="external"]').each(function(link) {
        if(link.readAttribute('href') != '' && link.readAttribute('href') != '#') {
            link.writeAttribute('target', '_blank');
        }
    });

    //-- Drop down languages
    if($j('.form-location li').size() > 1) {
        var locationHide = $j('.form-location .hide');
        var firstLocationSpan = $j('.form-location .first span:first');
        $j('.form-location a').mouseenter(function(){
            locationHide.show();
            firstLocationSpan.css({backgroundColor:'#e0d6b2'});
        }).mouseleave(function(){
            firstLocationSpan.css({backgroundColor:'transparent'});
            locationHide.hide();
        });
    } else {
        $j('.form-location li').each(function() {
            $j(this).css('opacity','0.5');
            $j('a',this)
                .click(function() { return false; })
                .css('cursor','default')
                .hover(function() { $j(this).css('color','#5a4a3d'); });
            $j('a span span', this).css('background', 'none');
        });
    }

   // Scroll-to-FAQ-question
   $j('.faqs ol li a').click(function() {
	   var target = $j(this).attr('href'),
	   topVal = $j(target).offset().top;
	   $j('html, body').animate({scrollTop: (topVal-20)+'px'}, 500);
	   //alert(topVal);
	   return false;
   });

   if($j('.faqs .sidebar').size() > 0 || $j('.product-details .sidebar').size() > 0) {
	   var sideTop = '<div id="side_top" class="back-to-top-side-wrapper"><a href="#" class="back-to-top-side"><span><span>Back to Top</span></span></a></div>';
	   $j('.sidebar .xoxo-first').after(sideTop);

	   var top = ($j('#side_top').css('marginTop')) ? $j('#side_top').offset().top - parseFloat($j('#side_top').css('marginTop').replace(/auto/, 0)) : $j('#side_top').offset().top;
	   $j(window).scroll(function (event) {
		   // what the y position of the scroll is
		   var y = $j(this).scrollTop();

		   // whether that's below the form
		   if (y >= top) {
			   // if so, add the fixed class
			   $j('#side_top').addClass('fixed');
		   } else {
			   // otherwise remove it
			   $j('#side_top').removeClass('fixed');
		   }
	   });
   }

    //-- Any fancybox calls need to go in this or else we'll have serious issues in IE
    if(jQuery.fn.fancybox) { 
           var fbonstart = ($j('.fancybox-ie').length != 0) ? function(){if($j('#fbiecssfix').length == 0) $j('head').append('<link id="fbiecssfix" rel="stylesheet" type="text/css" media="all" href="'+BASE_URL+'assets/fancybox/jquery.fancybox-1.3.1-iefix.css" />');} : null;

           if($j(this).attr('href') == '#testimonial_form') {
               $j('a.fancybox').fancybox({
                   'height':494,
                   'onStart': fbonstart,
                   'overflowColor':'#000',
                   'overlayOpacity':0.5,
                   'padding':30,
                   'autoScale': false
               });
           } else {
               $j('a.fancybox').fancybox({
                   'onStart': fbonstart,
                   'overlayColor':'#000',
                   'overlayOpacity':0.5,
                   'padding':30,
                   'autoScale': false
               });
           }

           $j('a.fancybox-iframe').fancybox({
               'onStart': fbonstart,
               'type' : 'iframe',
               'scrolling' : 'no',
               // 'autoScale': false,
               // 'autoDimensions': false,
               'height': 300,
               'width': 700,
               'overlayColor':'#000',
               'overlayOpacity': 0.5,
               'padding': 30
            });

           $j('a.fancybox-auto-resize').fancybox({
               'autoScale': false,
               'autoDimensions': false,
               'onStart': fbonstart,
               'height': 342,
               'width': 700,
               'overlayColor':'#000',
               'overlayOpacity': 0.5,
               'padding': 30
           });

           $j('a.fancybox-wide-auto').fancybox({
               'onStart': fbonstart,
               'overlayColor': '#000',
               'overlayOpacity': 0.5,
               'padding': 30
           });
           
           $j('a.fancybox-video').fancybox({
               'onStart': fbonstart,
               'overlayColor':'#000',
               'overlayOpacity':0.85,
               'padding':30,
               'height' : 225,
               'width'  : 400,
               'autoScale': false
           });

           $j('a.fancybox-video-popup').fancybox({
               'onStart': fbonstart,
               'overlayColor':'#000',
               'overlayOpacity':0.85,
               'padding':30,
               'height':610,
               'width':535,
               'autoDimensions':false,
               'autoScale': false
           });
            
            $j('a.fancybox-img').fancybox({
                'autoScale': false,
                'onStart': fbonstart,
                'overlayColor': '#000',
                'overlayOpacity': 0.5
            });

            $j('a.fancybox-share-buttons').fancybox({
                'autoScale' : false,
                'onStart' : fbonstart,
                'overlayColor' : '#000',
                'overlayOpacity' : 0.5,
                'padding' : 25,
                'height' : 33,
                'width' : 261,
                'autoDimensions' : false
            });

        }
        //-- End fancybox calls

       //-- Begin Cycle calls
       if($j('#slideshow').length) {
           var slideshow = $j('#slideshow');
           slideshow.cycle({
               fx: 'scrollLeft',
               pause: 1
           });
           $j('#slide:first').click(function() {
               slideshow.cycle('stop');
           });
       }

       //-- Back to top Links --//
       $j('a.back-to-top, a.back-to-top-side').live('click',function(){
           $j('html, body').animate({scrollTop: '0px'}, 300);
           return false;
       });

       // Home page slideshow
       if($j('.hero-banner-slideshow').size() > 0) {
           $j('.hero-banner-slideshow').cycle({
               delay:4000,
               fx:'fade',
               timeout:6000
           });
       }
       
       if (window.location.hash == '#show_languages') {
           jQuery(".fancybox-wide-auto").trigger('click');
       }
       
       if(window.location.hash == '#show_languages') {
           jQuery('[href="#select_languages"]').click();
       }

        if($j.browser.msie && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5), 10) == 6) {
            $j('body').children(':first-child').before('<div id="ie6msg"><h4>Did you know that your browser is out of date?</h4> <p>To get the best possible experience using our website we recommend that you upgrade your browser to a newer version. The current version is <a class="getie8" href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx">Internet Explorer 8</a> and <a class="getie9" href="http://windows.microsoft.com/en-us/internet-explorer/download/ie-9/worldwide">Internet Explorer 9</a> is available as a beta. The upgrade is free. If you’re using a PC at work you should contact your IT-administrator.</p>            <p>If you want to you may also try some other popular Internet browsers like <a class="opera" href="http://www.opera.com">Opera</a>, <a class="chrome" href="http://www.google.com/chrome">Chrome</a>, <a class="firefox" href="http://mozilla.com">FireFox</a> or <a class="safari" href="http://www.apple.com/safari/download/">Safari</a></p><p>Optionally, you may install the <a href="http://www.google.com/chromeframe">Google Chrome Frame plugin</a> which will allow your browser to load pages using the improved Google Chrome browser rendering engine.</p></div>');
        }

		// client side validation for testimonials
		if ($j('.testimonials').size() > 0) {
			$j(':submit.gform_button').click(function(event) {
				var recordingPath = $j('#recorder')[0].recordingPath();
				$j('.testimonials .gform_hidden input').val(recordingPath);

				var fieldChecks = [ { 'fieldType': ':text', 'condition': '!$j.trim($j(this).val())' }, { 'fieldType': ':checkbox', 'condition': '!$j(this).is(":checked")' } ];
				var requiredFieldsFilled = true;
				$j('.gfield_contains_required').each(function() {
					var container = $j(this);
					for (var i = 0; i < fieldChecks.length; i++) {
						var fieldType = fieldChecks[i].fieldType;
						var condition = fieldChecks[i].condition;
						$j(this).find(fieldType).each(function() {
							if (eval(condition)) {
								requiredFieldsFilled = false;;
								container.find('.ginput_container:first').after('<div class="gfield_description validation_message">This field is required.</div>');
							}
						});
					}
				});
				if (!requiredFieldsFilled) {
					$j('#testimonial-errors').show();
					return false;
				}
			});
		}
   });

if(typeof Prototype !== 'undefined') {
    // -- This must be inside of a load event vs the above dom:loaded to avoid an IE quirk
    Element.observe(Prototype.Browser.IE ? window : document, Prototype.Browser.IE ? 'load' : 'dom:loaded', function(event) {
         if(!$('loading-process')) {
             var loadingProcess = new Element('div', {'id':'loading-process'});
             Element.insert($$('body')[0], {bottom: loadingProcess});
         }
    });
}


