var $j = jQuery.noConflict(); // plays nice with Prototype library

var chow_logged_in = (document.cookie.indexOf('cs_sig') != -1) ? true : false;

// set these globally so they don't get obfuscated by the compressor
var mpu_1, mpu_2, small_site_promo, leaderboard, button, mantle_skin;

chow_js = {

	init: function(){

		// load login snippet
		if (loadLogin) {
			this.insertLoginSnippet();
		}

        this.header_listeners();

		// add these listeners even if logged in. lightboxes other than login/signup use them, as well
		chowLoginSignup.addLightboxListeners();

		// initialize login and signup lightboxes
		if (!loadLogin) {
			chowLoginSignup.init();
		}

		// set up form validators
		chow_validate_form.init();

		// add focus and blur handlers for default input values
		handle_default_text();

		// popup opener and closer
		// assumes <a href="#id_of_popup" class="open_popup">text</a>
		// assumes <a href="#id_of_popup" class="close_popup">text</a>
		this.popup_openers = $j('a.open_popup');
		this.popup_closers = $j('a.close_popup');
		this.popups = $j('.chow_popup').add($j('.chow_lightbox'));// all popups and lightboxes

		$j(this.popup_openers).click(function(e){
			e.preventDefault();
			// close any existing popups before opening a new one
			chow_js.close_popups();

			var popupId = this.href.split('#')[1];
			$j('#' + popupId).addClass('active');
		});

		$j(chow_js.popup_closers).click(function(e){
			e.preventDefault();
			chow_js.close_popups();
		});

		// close popups and lightboxes when Escape key is pressed
		$j(document).keydown(function(e){
			if( e.keyCode == '27' ){
				e.preventDefault();
				chow_js.close_popups();
			}
		});

		chow_slider.init();

  }, // init

  header_listeners: function() {
    var nav_timeout;
    var header_search_options_dropdown = $j('#header_search_options_dropdown');
    var header_search_options_selection = $j('#header_search_options_selection');
    var header_search_type = $j('#header_search_type');
    var header_search_board_options = $j(".header_search_board_option");
    var header_search_params_set = false;

    /// map urls to search type and search text (for header search dropdown)
    var path_names = {
        'food-news' : {search_type: 'Story', search_text: 'Stories'},
        'digest' : {search_type: 'Story', search_text: 'Stories'},
        'videos' : {search_type: 'Video', search_text: 'Video'},
        'recipes' : {search_type: 'Recipe', search_text: 'Recipes'},
        'boards' : {search_type: 'Topic', search_text: 'Chowhound'},
        'topics' : {search_type: 'Topic', search_text: 'Chowhound'},
        'default' : {search_type: '', search_text: 'Entire Site'}
    }

    // highlight top nav link based on url
    $j('.top_nav_link').each(function() {
      var href_value = $j(this).attr('href');
      if (window.location.pathname.indexOf(href_value) == 0
          || (window.location.pathname.indexOf('topics') != -1 && href_value == '/boards')  // special case for boards and topics
          || (window.location.pathname.indexOf('digest') != -1 && href_value == '/food-news/') ) // special case for digests and stories
      {
        $j(this).addClass('selected');
        set_header_search(href_value);
      }
    });

    // set header search to default values if not already set
    if(!header_search_params_set){
        set_header_search('default');
    }

    // open/close dropdown menus on hover or mouseout
    $j('#chow_top_nav_inner li').hover(
      function () {
        var element = this;
          nav_timeout = setTimeout(function(){$j('ul', element).slideDown(100)}, 200);
        },

        function () {
          clearTimeout(nav_timeout);
          $j('ul', this).slideUp(100);
        }
    );

    // open header search options
    $j('#header_search_options_selection, #header_search_options_arrow').click(function(){
        $j(header_search_options_dropdown).slideToggle(100);
    })

    // listen for click events on header search options
    // set search type and text to clicked value
    $j('.header_search_option').click(function(){
        $j(header_search_options_selection).html($j(this).html());
        $j(header_search_type).val( this.getAttribute('data-search-type') );
        $j(header_search_options_dropdown).slideUp(100);

        // enable/disable hidden fields for board options
        if($j(this).html() == 'Chowhound'){
           $j(header_search_board_options).attr('disabled', false);
        } else {
           $j(header_search_board_options).attr('disabled', true);
        }
    });

    function set_header_search(href_value){
        // set header search values based on url
        for (i in path_names){
            if (href_value.indexOf(i) != -1) {
                $j(header_search_options_selection).html(path_names[i].search_text);
                $j(header_search_type).val(path_names[i].search_type);
            }
        }

        header_search_params_set = true;
    }

  },

	insertLoginSnippet: function(){
	// write login/sign up links to header

		var links = '';
		var page_url = document.location.toString();

		if(chow_logged_in){
			// read cs_sig cookie and create links to profile and logout
			var cs_sig_info = document.cookie.split('cs_sig')[1].split(';')[0];
			var username = cs_sig_info.split('username%3D')[1].split('%26')[0];
			var user_id = cs_sig_info.split('id%3D')[1].split('%26')[0];


		    if($j('#chow_header.mobile')[0]){
			  links = '<a id="login_user_name" href="/profile/' + user_id + '">' + username + '</a>';
	        } else {
		      links = '<a id="login_user_name" href="/profile/' + user_id + '">' + username + ' (view profile)</a><span class="mr5 ml5">/</span>' +
		            '<a href="/account/logout?return_to=' + page_url + '" rel="nofollow">Log Out</a>';
	        }

		} else {
			// create login and signup links
			links = '<a href="/account/login?return_to=' + page_url + '" class="show_login_box" id="login_link" rel="nofollow">Log In</a> / ' +
	                '<a href="/users/sign_up?return_to=' + page_url + '" class="show_signup_box last" id="signup_link" rel="nofollow">Sign Up</a>'
		}
		$j('#header_login')[0].innerHTML = links;

		if(!chow_logged_in){
			chowLoginSignup.init();
		}

	},

	close_popups: function(){

		$j(chow_js.popups).removeClass('active');

		// hide error messages
		$j('.chow_error').hide();

		// reset any forms that have reset_on_close class
		$j('.reset_on_close').each(function(){
			this.reset();
		});
	}

}// chow_js


var chowLoginSignup = {
	init: function() {
		// add listeners if not logged in
		if(!chow_logged_in){
			this.add_listeners();
			this.new_location = ''; // redirects to new location on login success
		}
	},

	addLightboxListeners: function(){
		// close lightbox when close btn is clicked
		// assumes <a class="close_lightbox" href="#id_of_box_to_close">X</a>
		var lightbox_close_btns = $j('.close_lightbox');

		$j(lightbox_close_btns).click(function(e) {
			e.preventDefault();
			var id = this.href.split('#')[1];
			$j('#' + id).removeClass('active');

			// reset any forms that have reset_on_close class
			$j('.reset_on_close').each(function(){
				this.reset();
			});
		});
	},

	add_listeners: function() {

		// find all instances of .show_login_box
		var show_login_box = $j('.show_login_box');
		// open login lightbox
		$j(show_login_box).click(function(e) {
			e.preventDefault();
			var classNames = this.className;

			// check if clicked element needs to call an external function after logging in
			if(classNames.indexOf('on_success') != -1) { // assumes element has a class in the form of on_success_someObject.someFunction
				chowLoginSignup.externalSuccess = classNames.split('on_success_')[1].split(' ')[0];
			}

			chowLoginSignup.open_login(e.pageY);
			chowLoginSignup.new_location = (this.href !== undefined) ? this.href : '';
		});

		// find all instances of .show_signup_box
		var show_signup_box = $j('.show_signup_box');
		// open signup lightbox
		$j(show_signup_box).click(function(e) {
			e.preventDefault();
			chowLoginSignup.open_signup(e.pageY);
		});

		$j('#join_chow_link').click(function(e){
			e.preventDefault();
			$j('#chow_login').removeClass('active');
			chowLoginSignup.open_signup();
		});

	}, // end add_listeners


	open_login: function(pageY){
		// pageY is optional. It's the y-coordinate of the click event.
		if(pageY !== undefined && pageY > 500){
			// move login box slightly above where the click was
			$j('#chow_login').css('top', (pageY - 400) );
			// also need to move the signup box in case they click 'join chow' in the login box
			$j('#chow_signup').css('top', (pageY - 400) );
		} else {
			$j('#chow_login').css('top', 0);
			$j('#chow_signup').css('top', 0);
		}

		$j('#chow_login').addClass('active');
		$j('#login_name').focus();
	},

	open_signup: function(pageY){
		// pageY is optional. It's the y-coordinate of the click event.
		if(pageY !== undefined && pageY > 500){
			// move signup box slightly above where the click was
			$j('#chow_signup').css('top', (pageY - 400) );
		} else {
			$j('#chow_signup').css('top', 0);
		}

		$j('#chow_signup').addClass('active');
		$j('#user_name').focus();
	},


	submit_login_form: function() {
    chowLoginSignup.set_timezone();

		$j.ajax({
			url: '/users/sign_in',
			type: 'POST',
			data: $j('#login_form').serialize(),
			success: function(data){
				// don't redirect to login or sign up pages
				if(chowLoginSignup.new_location.indexOf('/account/combined') != -1 ||
					chowLoginSignup.new_location.indexOf('/account/login') != -1 ||
          chowLoginSignup.new_location.indexOf('/users/sign_in') != -1 ||
					chowLoginSignup.new_location.indexOf('/account/signup') != -1 ||
          chowLoginSignup.new_location.indexOf('/registrations/new') != -1 ||
          chowLoginSignup.new_location.indexOf('/get_access') != -1 ||
					chowLoginSignup.new_location == '') {
						chowLoginSignup.new_location = document.location.toString().split('#')[0];
				}
				// call external success function if it exists, otherwise refresh the page
				if(chowLoginSignup.externalSuccess){
					chow_logged_in = true;
					toggleSpinner('login_submit', 'show');
					$j('#chow_login').removeClass('active');

					// remove listeners from login links
					$j('.show_login_box').unbind('click');

					// update login/sign up links in header
					chow_js.insertLoginSnippet();


					if(chowLoginSignup.externalSuccess.indexOf('_params_') != -1 ){
						// externalSuccess can be in this form:
						// on_success_Topic.changeResponseArea_params_5880460_731285_1
						// which will get called as Topic.changeResponseArea("5880460","731285","1")
						// or you can pass a function with no params like this:
						// on_success_Topic.changeResponseArea

						var functionName = chowLoginSignup.externalSuccess.split('_params_')[0];
						var paramsArray = chowLoginSignup.externalSuccess.split('_params_')[1].split('_');
						var params = '';
						for(var i = 0; i < paramsArray.length; i++){
							params += '"' + paramsArray[i] + '"';
							if(i != paramsArray.length - 1){
								params += ',';
							}
						}
						eval(functionName + '(' + params + ')');
					} else {
						eval(chowLoginSignup.externalSuccess + '()');
					}

				} else {
                    if(chowLoginSignup.new_location == document.location){
                        window.location.reload();
					}else{
                        document.location = chowLoginSignup.new_location;
				    }
				}
			},

			error: function(data){

				toggleSpinner('login_submit', 'show');

				if(data.responseText.indexOf('Invalid email or password') != -1){
					$j('#login_error').html('The username or password you entered is incorrect.');

				} else if(data.responseText.indexOf('unknown_login_state') != -1){
					$j('#login_error').html('You need to verify your account with the email we sent you before you can log in. Contact <a href="mailto:moderators@chowhound.com" class="blue">moderators@chowhound.com</a> if you didn\'t recieve an email when you signed up');

				} else {
					$j('#login_error').html('Unexpected Error');
				}

				$j('#login_error').show();
			}

		}); // ajax
    return false;
	}, // end submit_login_form


	submit_signup_form: function() {

		chowLoginSignup.set_timezone();

		$j.ajax({
			url: '/users.js',
			type: 'POST',
			data: $j('#signup_form').serialize(),
			success: function(data){
				$j('#signup_header').html('Thanks for signing up!');
				$j('#signup_form').html('<p class="ml10 mr10 f12">We just sent a <strong>verification email</strong> to your email address. You\'ll need to open it and click the link to finish the registration process. (If you don\'t receive it, check your spam folder! If you still haven\'t received it email <a href="mailto:moderators@chowhound.com" class="blue">moderators@chowhound.com</a>.)</p>');
			},

			error: function(data){
				toggleSpinner('signup_submit_lightbox', 'show');
				$j('#signup_error').html(data.responseText).show();
			}

		}); // ajax

	}, // end submit_signup_form

	set_timezone: function(){
		var offset = -(new Date()).getTimezoneOffset()*60;
		$j('#login_timezone')[0].value = offset;
		$j('#signup_timezone')[0].value = offset;
	}

} // end chowLoginSignup

var chowLoginSignupReady = true;

function handle_default_text(){
// adds focus and blur listeners to clear and set default field text
// called as part of chow_js.init()
// USAGE: add class 'has_default_text' to your element
// add attribute 'data-default-text' to your element
// EXAMPLE: <input type="text" class="has_default_text" data-default-text="Headline" value="Headline" />

	$j('.has_default_text').each(function(){
		$j(this).focus(function(){
			if(this.value == this.getAttribute('data-default-text') ){
				this.value = '';
			}
		});

		$j(this).blur(function(){
			if(this.value == '' ){
				this.value = this.getAttribute('data-default-text');
			}
		});
	});
}


var chow_validate_form = {
	// this function validates form input and shows error messages

	// USAGE: add a class of 'validate_form' to your form element
	// If you have a submit handler that you want to call after the error checks pass,
	// add an attribute to your form element called 'data-submit-handler'.
	// if there's a submit btn click listener you want to add,
	// add an attribute to your form element called 'data-submit-btn-id'.

	// For example, the login lightbox looks like this:
	// <form class="validate_form reset_on_close" data-submit-handler="chowLoginSignup.submit_login_form()" data-submit-btn-id="login_submit" id="login_form">


	// add the following classes to your input elements

	// .required  - set this class on a field that can't be blank
	// .required_checkmark - this class ensures a checkbox has a checkmark (agree to terms of use, for example)
	// .validate_username: - during sign up, ensures username is be between 5 and 20 characters with no special characters or spaces
	// .validate_password - password must have at least 5 characters
	// .confirm_password - the value of this field must match the value of the .validate_password field
	// .validate_email - ensures input is in the form of somename@someaddress.something
	// .validate_phone - ensures a phone number has 10 digits with optional parentheses, dashes, dots or spaces

	// error messages will be pulled from the errorMessages object below
	// or you can set a custom message in the data-error-msg attribute:
	// <input type="checkbox" id="agree_to_terms" data-error-msg="Please agree to our terms of service" />
	// or you can override the default messages: <script>chow_validtae_form.errorMessages.required = "Do it Right!"</script>

	// all inputs that require validation must have an id so an error message holder can be inserted after it
	// error message will be <div class="chow_error" id="[parent_id]_error">chow_validtae_form.errorMessages[messageType]</div>

	errorMessages: {
		//default error messages
		required: "This field can't be blank",
		required_checkmark: "Please check the box", // TODO: make this message less lame
		validate_username: "Username must be between 5 and 20 characters with no special characters or spaces",
		validate_password: "Password must be at least 5 characters",
		confirm_password: "Both passwords must match",
		validate_email: "Invalid email address",
		validate_phone: "Phone number must have 10 digits"
	},

	init: function(){
		$j('form.validate_form').each(function(){
			var theForm = this;

			// handle submit event
			$j(this).submit(function(e){
				e.preventDefault();
				chow_validate_form.run_validations(this);
			});

			// handle click event
			if(this.getAttribute('data-submit-btn-id')){
				$j('#' + this.getAttribute('data-submit-btn-id')).click(function(e){
					e.preventDefault();
					chow_validate_form.run_validations(theForm);
				});
			}

		});

	},

	run_validations: function(theForm){
		this.form = theForm;

		// hide error messages
		$j('.chow_error', this.form).hide();

		// flag that gets set to false if there's an error
		this.passed_validation = true;


		// find the inputs to run the validations against
		this.required = $j('.required', this.form);
		this.required_checkmark = $j('.required_checkmark', this.form);
		this.validate_username = $j('.validate_username', this.form);
		this.validate_password = $j('.validate_password', this.form);
		this.confirm_password = $j('.confirm_password', this.form);
		this.validate_email = $j('.validate_email', this.form);
		this.validate_phone = $j('.validate_phone', this.form);


		// REQUIRED: show error for required fields that are blank
		$j(this.required).each(function(){
			if ( $j.trim(this.value).length == 0 ){
				chow_validate_form.insert_error_message(this, 'required');
			}
		});

		// REQUIRED CHECKMARK: show error if checkbox is not checked
		$j(this.required_checkmark).each(function(){
			if ( this.checked != true ){
				chow_validate_form.insert_error_message(this, 'required_checkmark');
			}
		});

		// VALIDATE_USERNAME: signup username must be between 5 and 20 characters with no spaces or special characters
		$j(this.validate_username).each(function(){
			if ( this.value.length < 5 || this.value.length > 20 || !this.value.match(/^\w+$/i) ){
				chow_validate_form.insert_error_message(this, 'validate_username');
			}
		});

		// VALIDATE PASSWORD: show error if password is less than 5 characters
		$j(this.validate_password).each(function(){
			if ( this.value.length < 5 ){
				chow_validate_form.insert_error_message(this, 'validate_password');
			}
		});

		// CONFIRM PASSWORD: show error if .confirm_password field doesn't match .validate_password field
		$j(this.confirm_password).each(function(){
			if ( this.value != chow_validate_form.validate_password[0].value ){
				chow_validate_form.insert_error_message(this, 'confirm_password');
			}
		});

		// VALIDATE EMAIL: show error if input is not in the form of somename@someaddress.something
		$j(this.validate_email).each(function(){
			if ( !( this.value.match(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,5}\b/) ) ){
				chow_validate_form.insert_error_message(this, 'validate_email')
			}
		});

		// VALIDATE PHONE: check for 10 digit phone number. valid formats: (555)555-5555, 555-555.5555, 555 555 5555, 5555555555
		$j(this.validate_phone).each(function(){
			if ( !( this.value.match(/\b\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})\b/) ) ){
				chow_validate_form.insert_error_message(this, 'validate_phone');
			}
		});


		if (this.passed_validation){
			// hide submit btn, show spinner
			if(this.form.getAttribute('data-submit-btn-id') ){
				toggleSpinner(this.form.getAttribute('data-submit-btn-id'), 'hide');
			}

			if(this.form.getAttribute('data-submit-handler') ){
				// call submit handler
				eval(this.form.getAttribute('data-submit-handler'))
			} else {
				// submit form
				this.form.submit();
			}
		}
	},

	insert_error_message: function(el, msg){
		// Use this function to insert an error message after an element.
		// el is the element that has the error. it can be a reference to the element or an id
		// msg is the error message. It can be a property of chow_validate_form.errorMessages or it can be a custom string.
		// You can also create a custom message by adding a data-error-msg attribute to your element like so:
		// <input type="checkbox" class="required_checkmark" data-error-msg="Check the box!" />
		// The message will be inserted after el unless you add data-insert-error-after to your element.
		// For example, the error message will be inserted after the submit btn instead after the input field:
		// <input class="validate_email" data-insert-error-after="getNewsForm_submit" id="newsEmail"  type="text" />
		// <input type="submit" id="getNewsForm_submit"/>

		var elm = (typeof el == "string") ? $j('#' + el)[0] : el;
		var error_message = chow_validate_form.errorMessages[msg] ? chow_validate_form.errorMessages[msg] : msg;
		error_message = (elm.getAttribute('data-error-msg') != undefined ) ? elm.getAttribute('data-error-msg') : error_message;
		var insert_here = (elm.getAttribute('data-insert-error-after') != undefined ) ? elm.getAttribute('data-insert-error-after') : el;
		insert_here = (typeof insert_here == "string") ? $j('#' + insert_here)[0] : insert_here;

		// find error container for this element if it exists
		var error_container = $j('#' + elm.id + '_error');

		// insert new error container into DOM if it doesn't exist
		if ( error_container.length == 0 ){
			$j(insert_here).after('<div class="chow_error" id="' + elm.id + '_error">' + error_message + '</div>');
			$j('#' + elm.id + '_error').show();

		// otherwise, update error message and show it
		} else {
			$j(error_container).html(error_message).show();
		}

		this.passed_validation = false;
	}
} // end chow_validate_form



var newsletterSignup = {

	submit_sidebar_form: function(){

		var userEmail = $j('#newsEmail')[0].value;

		//if logged in, forward to newsletters in profile
		if (chow_logged_in) {
			window.location = '/newsletters';

		//xhr to see if they are an existing user
		} else {

			//check if email address already exists
			$j.ajax({
				url: '/newsletters/check_email',
				type: 'POST',
				data: {email: userEmail},
				success: function(data){// response - 'email_in_use' 200.  known email user, no account or 'email_ok' 200 unknown user
					$j('#newsletter_email')[0].value = userEmail;
					$j('#newsletter_signup').addClass('active');
					toggleSpinner('getNewsForm_submit', 'show');
				},

				error: function(data){ //error means that the email exists and we want to log them in (response - 'email_in_use' 200 known user with account)
					$j('#login_name')[0].value = userEmail;
					if ( !$j('#login_to_newsletters')[0] ) { //add instructions once in Log In box and add invisible link to click and launch login
						$j('<div id="login_to_newsletters" class="f14 bold mt5">Manage Newsletter Preferences</div>').insertAfter('#login_header');
					}

					var tempUrlHolder = $j('#login_link').attr('href');//pull href out of login
					$j('#login_link').attr('href', '/newsletters').click(); //substitute href in login and click it
					$j('#login_link').attr('href', tempUrlHolder);//replace original login href
					toggleSpinner('getNewsForm_submit', 'show');
				}
			});
		}
	},

	submitForm: function() {

		// add custom validation
		if ( $j('#newsletters_form input:checked').length == 0 ) {
			chow_validate_form.insert_error_message( 'select_a_newsletter', 'Select at least one newsletter' );

			// show submit btn
			toggleSpinner('newsletter_submit_lightbox', 'show');
			return;
		}

		// change sidebar email value to match popup
		$j('#newsEmail')[0].value = $j('#newsletter_email')[0].value;

		// set the response header so the return value doesn't throw an undefined variable error
		jQuery.ajaxSetup({
			'beforeSend': function(xhr) {
			  xhr.setRequestHeader("Accept", "text/javascript")
			}
		});


		$j.ajax({ //check the email address if it already exists
			url: '/newsletters/check_email',
			type: 'POST',
			data: {email:$j('#newsletter_email')[0].value},
			success: function(data){
				$j.ajax({ //sign user up
					url: '/newsletters/standalone_update_subscriptions',
					type: 'POST',
					data: $j('#newsletters_form').serialize(),
					dataType: 'text',
					success: function(data){
						toggleSpinner('newsletter_submit_lightbox', 'show');
						$j('#newsletter_signup_header').html('Thanks for signing up!');
						$j('#newsletters_form').html('<p id="newsThanks" class="ml10 mr10 f12">You\'ve successfully signed up for CHOW Newsletter. To adjust your email preferences, click the <strong>Manage Your Subscription</strong> link at the bottom of any CHOW Newsletter.</p>');
						$j('#getNewsletters').html('<span class="f14">Thanks for signing up!</span>');
						$j('#getNewsForm').hide();
					},

					error: function(data){
						toggleSpinner('newsletter_submit_lightbox', 'show');
						$j('#newsletter_signup_error').html('Error, Please refresh the page and try again.');
					}

				}); // user sign up ajax
			},

			error: function(data){
				toggleSpinner('newsletter_submit_lightbox', 'show');
				chow_validate_form.insert_error_message( 'newsletter_email', 'Email address already taken' );
			}

		}); // check the email address ajax

	}	/*submitForm*/
} /*newsletterSignup*/






function toggleSpinner(id, visibility){

	// insert spinner if it doesn't exist
	if( $j('#' + id + '_spinner').length == 0 ){
		// give the spinner the same clases as the submit btn except for 'chow_btn'
		var spinner_classes = $j('#' + id)[0].className;
		spinner_classes = spinner_classes.replace(/chow_btn/, '');
		$j('#' + id).after('<img id="' + id + '_spinner" class="' + spinner_classes + '" src="/images/spinner-small-orange.gif" width="16" height="16" />');
	}

	// hide submit btn, show spinner
	if( visibility == 'hide') {
		$j('#' + id).hide();
		$j('#' + id + '_spinner').show();
	} else {
	// show submit btn, hide spinner
		$j('#' + id).show();
		$j('#' + id + '_spinner').hide();
	}

}


function doNothing(){
	return;
	// google maps api calls this. It prevents their script from doing a document.write()
}


// CHOW click handler: same as default except when redirecting,
// in which case, do not append "tag="

function chowClickHandler(e) {
    // Don't use "this" keyword in this function unless you
    // want to access the element the event is associated with.
    // Use 'DW' to access methods in the DW object.

    // Get the target of the event.
    var target = DW.getEventTarget(e);

    // And the link
    var linkObj = DW.getLinkObject(target);

    // Bail if there was no link (which is common), or if we should ignore it,
    // or if we already have a tag and it's internal,
	// (CHOW-ENG) - added $j.hasClass(linkObj,'notrack')
    if ($j(linkObj).hasClass('notrack') || null == linkObj || DW.ignoreClick(linkObj) || (DW.isInternalLink(linkObj) && DW.hasTagParam(linkObj))) {
        return;
    }

    // Ok, build our tag now
    var tag = DW.buildTag(target);

    var isRedirect = linkObj.href.indexOf("chow.com/action/rd2") != -1;//TODO: replace with prefix variable

    // TODO: add "and not to redirector" to if statement below
    if (DW.isInternalLink(linkObj) && !isRedirect) {
        // Internal. Just add the tag, let the link do it's thing
        DW.addTag(linkObj, tag);
    } else {
        // External. Track it in the background using
        DW.trackClickInBackground(linkObj, tag, target.nodeName, e.type);
    }
}

var chow_slider = {
	init:function(){
		var sliders = $j('.chow_slider');
		for(var i=0; i<sliders.length; i++){
			chow_slider.addListeners(sliders[i]);
		}
	},

	addListeners : function(slider) {
		// use local vars instead of object properties or else multiple sliders on the same page will get confused
		var thumb_links = $j('a.slider_link', slider);
		if(thumb_links.length == 0) return; // prevent js errors if the slider is empty due to DB or solr problems
		var thumb_total = thumb_links.length;
		var thumb_description = $j('span.slider_hover_text', slider)[0]; // container for hover text
		var temp = $j('li.slider_item', slider)[0];
		var thumb_width = parseInt($j(temp).css('width'));
		var margin_width = parseInt($j(temp).css('marginRight'));
		thumb_width += margin_width;
		temp = $j('a.slider_btn', slider);
		var left_button = temp[0];
		var right_button = temp[1];
		var left_button_width = parseInt($j(left_button).css('width'));
		left_button_width += parseInt($j(left_button).css('marginRight'));
		var slider_inner = $j('ul.slider_inner', slider)[0];

		// number of visible thumbs per slider type
		if($j(slider).hasClass('narrow_slider') ){var thumbs_per_set = 3}
		if($j(slider).hasClass('medium_slider') ){var thumbs_per_set = 4}
		if($j(slider).hasClass('wide_slider') ){var thumbs_per_set = 8}

		var first_visible = 0; // keeps track of first visible thumb
		var last_visible = thumbs_per_set; // keeps track of last visible thumb

		// hide right button if there's nothing to scroll to
		if(thumb_total <=thumbs_per_set){
			$j(right_button).addClass('end')
		}

		//thumb mouseover
		$j(thumb_links).mouseover(function(e) {
			var position = parseInt(this.getAttribute('pos'));
			if(thumb_description) {
				thumb_description.innerHTML = this.rel;
				thumb_description.style.display = "block";
				var left_position =  (position - first_visible) * thumb_width + left_button_width;

				// align thumb description to the right of thumb if we are in the second half of visible thumbs
				if ( (last_visible - position) <= (thumbs_per_set/2) ){
					$j(thumb_description).addClass('end');
					thumb_description.style.left = left_position + thumb_width - margin_width - thumb_description.offsetWidth + "px";
					thumb_description.style.backgroundPosition = thumb_description.offsetWidth -8 +"px -1144px";
				} else {
					// align description with the left of the thumb
					thumb_description.style.left = left_position + 'px';
				}
			}
		});

		//thumb mouseout
		$j(thumb_links).mouseout(function(e) {
			if(thumb_description) {
				thumb_description.style.display = "none";
				$j(thumb_description).removeClass('end');
				thumb_description.style.backgroundPosition = "0 -1144px"; //reset chevron
			}
		});


		// Right Button
		$j(right_button).click(function(e) {
			e.preventDefault();
			if (last_visible < thumb_total) {
				var max_scroll_left = thumb_total - last_visible;
				var scroll_left_by = (max_scroll_left >= thumbs_per_set)? thumbs_per_set : max_scroll_left;
				//var right_slider_attributes = {left: { by: -(scroll_left_by * thumb_width) }};
				var newLeftPosition = parseInt($j(slider_inner).css('left')) - (scroll_left_by * thumb_width)

				$j(slider_inner).animate(
					{left: newLeftPosition},
					{duration: 1000,
					queue: false,
					complete: function(){
						last_visible = last_visible + scroll_left_by;
						first_visible = first_visible + scroll_left_by;
						$j(left_button).removeClass('end');
						if(last_visible == thumb_total){
							$j(right_button).addClass('end')
						}
					}
				});
			}
		});



		// Left Button
		$j(left_button).click(function(e) {
			e.preventDefault();
			if (first_visible > 0) {
				var scroll_right_by = (first_visible > thumbs_per_set  ) ? thumbs_per_set : first_visible;
				var newLeftPosition = parseInt($j(slider_inner).css('left')) + (scroll_right_by * thumb_width)

				$j(slider_inner).animate(
					{left: newLeftPosition},
					{duration: 1000,
					queue: false,
					complete: function(){
						last_visible = last_visible - scroll_right_by;
						first_visible = first_visible - scroll_right_by;
						$j(right_button).removeClass('end');
						if(first_visible == 0) {
							$j(left_button).addClass('end');
						}
					}
				});
			}
		});
	}
} // end chow_slider


var	share_side_bar = {
	init: function(isMobile) {
		this.mobile = isMobile || false;
		// page_title, permalink, header_image, and gigyaApiKey are js vars set on the page
		// insert Gigya script
		var gigyaScript = document.createElement('script');
		gigyaScript.type = 'text/javascript';
		gigyaScript.src = 'http://cdn.gigya.com/JS/socialize.js?apikey=' + gigyaApiKey;
		document.getElementsByTagName("head")[0].appendChild(gigyaScript);

		// insert Twitter script
		var twitterScript = document.createElement('script');
		twitterScript.type = 'text/javascript';
		twitterScript.src = 'http://platform.twitter.com/widgets.js';
        document.getElementsByTagName("head")[0].appendChild(twitterScript);

        if(! this.mobile){
			this.share_bar = $j('#share_side_bar')[0];
            this.contentWidth = 1090;

			// animations to maximize/minimize share bar
			function expand_sharebar(){
				$j(share_side_bar.share_bar).animate(
					{left: 0},
					{duration: 333,
					complete: function(){
						$j('#share_bar_tab').hide();
					}
				});
			}

			function minimize_sharebar(){
				$j(share_side_bar.share_bar).animate(
					{left: -60},
					{duration: 333,
					complete: function(){
						$j('#share_bar_tab').show();
					}
				});
			}


			// minimize share bar if window is narrower than content area
			if(document.body.offsetWidth < this.contentWidth || window.innerWidth < this.contentWidth){
				minimize_sharebar();
			}

			// minimize share bar if it overlaps content
			$j(window).resize(function(e) {
				var windowWidth = window.innerWidth || document.body.offsetWidth;
				if (windowWidth < share_side_bar.contentWidth){
					minimize_sharebar()
				} else { // expand share bar
					expand_sharebar()
				}
			});

			// expand minimized share bar
			$j(share_side_bar.share_bar).mouseover(function(e) {
				if(this.style.left == '-60px')
					expand_sharebar();
			});

			// minimize share bar
			$j(share_side_bar.share_bar).mouseout(function(e) {
				if(this.style.left == '0px' && (document.body.offsetWidth < share_side_bar.contentWidth || window.innerWidth < share_side_bar.contentWidth)){
					if(!share_side_bar.contains(this, e.relatedTarget || window.event.toElement)){
						if (!e) var e = window.event; //IE
						e.cancelBubble = true; //IE
						if (e.stopPropagation) e.stopPropagation();
						minimize_sharebar();
					}
				}
			});

			// listen for scroll event and set position of share bar
			$j(window).scroll(function(e) { // IE doesn't recognize document scroll, just window
				var currentOffset = document.documentElement.scrollTop || document.body.scrollTop;

				if (currentOffset >= 180){
					share_side_bar.share_bar.style.position = 'fixed';
					share_side_bar.share_bar.style.top = '20px';
				} else {
					share_side_bar.share_bar.style.position = 'absolute';
					share_side_bar.share_bar.style.top = '200px';
				}
			});
		} // not mobile
	},

	// write email button and share link after gigya js loads
	writeShareLinks: function(){
		if(! share_side_bar.mobile){
			$j('#share_bar_gigya')[0].innerHTML = '<a href="#" class="f12 bold" onclick="showGigya(\'share_bar_gigya\'); return false">' +
				'<span class="f14 block">+</span>SHARE</a>';
		}

	  //  write email button for main column email links
		$j('.gigya_email').each(function(i) {
		    $j(this).html('<a class="gigya_email_link" href="#" onclick="showGigya(this);return false" >' +
				'<img class="gigya_email_img" width="16" height="12" class="mr5" alt="Email" src="http://cdn.gigya.com/gs/i/Share/EmailIcon.png">Email</a>');
		});
	},

	// helper method for mouseout. iterates up through parents until a match is found or it reaches <html> tag
	contains: function(e, c){
		return (e == c) ? true : ((c.parentNode) ? share_side_bar.contains(e, c.parentNode) : false);
	}
}


//Gigya
function showGigya(clickObj){
	var conf = {
		APIKey: gigyaApiKey,
		cid: "CHOW.com"
	};
	var initial_view = 'default';

	if($j(clickObj).parent().hasClass('gigya_email')){
		initial_view = 'email'
	}


	// spinner for share and email link
	$j(clickObj).html('<img src="http://www.chow.com/images/spinner-small-orange.gif" width="16" height="16" class="m5"/>');

	// Constructing a UserAction Object
	var act = new gigya.services.socialize.UserAction();


	// Setting the User Message
	act.setUserMessage("Check out this Story on CHOW.com:\n" + page_title + "\n" + permalink);

	// Setting the Title. Also used for email subject
	act.setTitle('Shared from CHOW: ' + page_title);

	// Adding a Link Back
	act.setLinkBack(permalink);

	// Setting the Description
	//act.setDescription("This is my Description");

	// Adding a Media (image)
	act.addMediaItem( {
		type: 'image',
		src: header_image,   // URL to the image source
		href: permalink    // URL to redirect the user when he clicks the image
	});

	// Activate the Share Plugin
	gigya.services.socialize.showShareUI(conf, {
		userAction: act,
		grayedOutScreenOpacity: 50,
		showEmailButton: true,
		initialView: initial_view,
		onLoad: share_side_bar.writeShareLinks // replace spinner with link
	});

}
// called when gigya js finishes loading
function onGigyaServiceReady() {
	share_side_bar.writeShareLinks();
}



var refreshableAds = {
	init: function() {

	cbsiSetDeferredLocalPage('/static/html/MantaRay_LocalPage.html');

	if ( $j('#mpu_1')[0] ) {
		if ( !(mpu_1) ) {
			mpu_1 = {
				'SP' : '16',
				'POS' : '100',
				'WIDTH' : '300',
				'HEIGHT' : '250',

				'REFRESH' : '1' // Default is 0.  Set to 1 to allow the ad to refresh.
		   };
			 if ( $j('#home')[0] ) { //adds extra propery to the mpu so we can use the onload callback
			   mpu_1.CALLBACK={onload: refreshableAds.mpu_1_callback};
			 }
		}
		cbsiSetupAdDiv("mpu_1", mpu_1);
	}

	if ( $j('#mpu_2')[0] ) {
		// the js gets set in topics/show
		// since the pos changes based on number of posts
		cbsiSetupAdDiv("mpu_2", mpu_2);
	}

    if ( $j('#small_site_promo')[0] ) {
		if ( !(small_site_promo) ) {
			small_site_promo = {
				'SP' : '63',
				'POS' : '100',
				'WIDTH' : '234',
				'HEIGHT' : '60',
				'REFRESH' : '1' // Default is 0.  Set to 1 to allow the ad to refresh.
			};
		}
		cbsiSetupAdDiv("small_site_promo", small_site_promo);
	}

	if ( $j('#leaderboard')[0] ) {
	  if ( !(leaderboard) ) {
			leaderboard = {
				'SP' : '15',
				'POS' : '100',
				'WIDTH' : '728',
				'HEIGHT' : '90',
				'REFRESH' : '1' // Default is 0.  Set to 1 to allow the ad to refresh.
			};
		}
		cbsiSetupAdDiv("leaderboard", leaderboard);
	}

	if ( $j('#button')[0] ) {
	  if ( !(button) ) {
			button = {
				'SP' : '162',
				'POS' : '100',
				'WIDTH' : '300',
				'HEIGHT' : '100',
				'REFRESH' : '1' // Default is 0.  Set to 1 to allow the ad to refresh.
			};
		}
		cbsiSetupAdDiv("button", button);
	}


	/* WE MAY NEED THIS AGAIN
	if ( !($j('#mantle_skin_ad_call')[0]) && !mantle_skin ) {
	  var mantle_skin_ad_call = document.createElement('div');
	  mantle_skin_ad_call.id = "mantle_skin_ad_call";
	  $j('#mantle_skin').prepend(mantle_skin_ad_call);

			mantle_skin = {
				'SP' : '119',
				'POS' : '100',
				'REFRESH' : '1' // Default is 0.  Set to 1 to allow the ad to refresh.
		};
		cbsiSetupAdDiv("mantle_skin_ad_call", mantle_skin);
	}
	*/

	cbsiRegisterAdGlobals(cbsiAdGlobal);
	// Load/Refresh All deferred ads in the page
	cbsiGetDeferredAds();
	},

	//shows home page video if ad is not loaded
	mpu_1_callback: function(callbackArr) {
      //console.log("******mpu_1_callback");
		if (callbackArr.isBlank == 1) {
            //console.log("******show video: callbackArr=" + callbackArr);
			$j('#sidebar').css('height', '423px');
			$j('#home_page_video').show();
		}
	}

}




var ch_mobile_tabs = {
	init:function(){

        var tabs = $j('.ch_tabs_item a');
        var tabContent = $j('.ch_mobile_nav');

        $j(tabs).click(function(e){
            e.preventDefault();
            var content_id = this.href.split('#')[1];
            $j(tabs).removeClass('selected');
            $j(this).addClass('selected');
            if ($j("#" + content_id).is(":visible")){
              $j(tabContent).slideUp(300);
              $j(this).removeClass('selected');
            } else {
              $j(this).addClass('selected');
              $j(tabContent).slideUp(300);
              $j("#" + content_id).slideDown(300);
            }
        });

	}
}
