var fullDomain = window.location.host;
var domainArray = fullDomain.split('.');
var subDomain=domainArray[0];
var mojax_request = 'none';
var previous_status;
var watch_for_crash;

if(subDomain == 'frintr'){
  subDomain = '';
}else{
  subDomain = subDomain + '.';
}

var tweet="";
var frint_url = 'http://' + subDomain + 'frintr.com/' + frint_permalink;

var fb_feed_form_attachment;
var fb_feed_form_description = 'Frintr can use the little profile pics of all your friends from Facebook, Myspace and Twitter and build a mosaic that, when viewed from a distance, appears to be your own profile picture. Very clever!';
var fb_feed_form_name = 'A mosaic made from all of ' + first_name + '\'s friends';

$(document).ready( function(){

  //$('body').ajaxError( function(e, xhr, settings, exception){
    //alert(xhr.status);
  //});

	rid = $(".frint_loading_status").attr('id'); //used to construct AJAX polling URL for Modis process
  $.ajaxSetup({ cache: false });

  fb_feed_form_attachment = {
    'name': fb_feed_form_name,
    'href': frint_url,
    'description': fb_feed_form_description,
    'media': [{
      'type': 'image',
      'src': 'http://' + subDomain + 'frintr.com/' + frint_permalink + '_small.jpg',
      'href': frint_url
    }]
  };

  $(".facebook_button.not_signed_in").click(function(){
		mojax_abort();
		FB.getLoginStatus(function(response){
		  //console.log(response.authResponse);
        if (response.authResponse == null){
          FB.login(function(response) {
            if(response.authResponse.accessToken){
              setCookie("FBlogin", "true");
              window.location.href = post_login_redirect;
            } else {
              // user cancelled login
            }
          });
        }else{
          setCookie("FBlogin", "true");
          window.location.href = post_login_redirect;
        }
    });
    return false;
  });

  $(".myspace_button.not_signed_in").click(function(){
		mojax_abort();
    MySpaceLogin();
    return false;
  });

  $(".twitter_button.not_signed_in").click(function(){
		mojax_abort();
    openPopup(twitterURL);
    return false;
  }); 

  $('.file_input_wrapper input[type=file]').bind('change focus click', fileInputs);
  
  $(".colorbox").colorbox();

	$(".add_to_cart").click( function(){ addToCart(this); return false; } );

	$(".decrease_quantity").live('click', function(){ doToCheckout(this, 'subtract'); return false; } );
	$(".increase_quantity").live('click', function(){ doToCheckout(this, 'add'); return false; } );
	$(".remove_product").live('click', function(){ doToCheckout(this, 'remove'); return false; } );

    //resize the twitter search text to fit
    $("#frint_pre").textfill({ maxFontPixels: 500 });

	//Fetch the frint via AJAX on page load only if the following selector exists though
	if( $("#users_frint.mojaxable").length ){	mojax(); }

	$("#frint_advice h3 a").click( function(){
		$("#frint_advice div").slideToggle();
		return false;
	});

	//Bind the button to rebuild the frint
	$("#frint_rebuild").click( function(){
		mojax('rebuild'); return false;
	});

	//Bind the consent functionality to place a Frint in the public library
	$("#consent a").click(function(){
    var fid = $("#consent a").attr('id');
    $.get('/frint/consent?fid=' + fid, function(data){
      if(data.error){
        //
      }else{
        if(data == 'success'){
          $("#add_this_frint").hide();
          $("#library_thankyou").show().highlightFade({color:'green', speed:2000, end:'white'});
        }
      }
    });
    return false;
	});

  $("#fb_feed_form a").click( function(){ fb_frint_feed_form(); return false; });

  $("#tweet_frint a").click( function(){
    tweet = $('#post_render_stuff textarea').html();
    //alert(frint_url);
    $.post('/create/tweet', { subDomain: subDomain, frint_url: frint_url, tweet: tweet }, function(data){
      if(data == 'success'){
        $('#tweet_frint textarea').fadeOut();
        $('#tweet_frint a').fadeOut();
        $('#tweet_frint span').show().highlightFade({color:'green', speed:2000, end:'white'});
      }else{
        //
      }
    });
    return false;
  });

	if(subDomain == 'xdev.'){
		$("#equation").click( function(){
			FB.login(
				function(response) {
					if (response) {
						result = response.perms.split(',');
						alert(result);
					}
				},
				{perms: 'friends_photos'}
			);
			return false;
		});
	}

  //Intercept the file upload submission on the tweak section to begin the uplaod progress indicator
  //$("#create_tweak form").bind('submit', function(){
  //  $("#uploading").fadeIn();
  //});

  bindings_for_checkout();

  if($().getTwitter){
    $("#twitter_feed").getTwitter({
      userName: "frintr",
      numTweets: 5,
      loaderText: "Loading tweets...",
      slideIn: true,
      slideDuration: 750,
      showHeading: true,
      headingText: "",
      showProfileLink: false,
      showTimestamp: true
    });
  }

  if($().validate){
    $("form[name=image_upload]").validate({
      rules: {
        file: {
          required: true,
          accept: "png|jpg|jpeg"
        }
      },

      messages: {
        file: {
          accept: "Sorry you can only upload JPG and PNG images"
        }
      },
      
      errorPlacement: function(error, element) {
        error.appendTo("form[name=image_upload]");
      },

      submitHandler: function(form){
        $("#upload_spinner").show();
        $("#upload_submit").hide();
        document.forms["image_upload"].submit(); //use native submit() to prevent recursion!
      }
    });
  }

  if($().validate){
    
    $.validator.setDefaults({ onkeyup: false });
    
		$.validator.addMethod("atLeastOneSN", function(value, element) {
			$('label.error').hide();
			mojax_abort();
			$("#frint_loading").hide();
			var SNs = $("#rebuilder .includeSN:checked");
			return SNs.length > 0;
		}, "You must choose at least 1 Social Network");
		
		$.validator.addMethod("twitterSearchCheck", function(value, element) {
		  
		  if($("#TWs_used:checked").val() != 'on'){
		    return true;
		  }
		  
      return $.validator.methods.remote.apply(this, arguments);
      
    }, $.validator.messages.remote);

		$("#rebuilder").validate({
      rules: {
        atLeastOneSN: {
          atLeastOneSN: true
        },

        TW_source: {
					remote: {
						url: '/main/twitterHandleCheck',
            beforeSend: function(data){
              $("#rebuild_spinner").show();
              $("#rebuild_submit").hide();
            },
						complete: function(data){
							$("#rebuild_spinner").hide();
              $("#rebuild_submit").show();
						}
					}
				},
				
				TW_search: {
          twitterSearchCheck:{
            url: '/main/twitterSearchCheck',
            beforeSend: function(){
              $("#rebuild_spinner").show();
              $("#rebuild_submit").hide();
            },
            complete: function(data){
              $("#rebuild_spinner").hide();
              $("#rebuild_submit").show();
              if(data.responseText == 'true') $("#rebuilder").submit();
            }
          }
        }
      },
      
      messages: {
        TW_source: "User doesn't exist",
				TW_search: "That search doesn't have enough results"
			}

    });
  }
  
  
  //Only 'turn on' the form once JS is working (hopefully prevents some spam botting) 
  $('#create_anon_searches input[name="preventSubmission"]').val('0');
  
	if($().validate){
	  
    $.validator.setDefaults({ onkeyup: false });
		$("#create_anon_searches").validate({

			rules: {
        TW_search: {
          remote: {
            url: '/main/twitterSearchCheck',
            beforeSend: function(data){
              $("#tw_search_spinner").show();
              $("#create_anon_searches .button").hide();
            },
            complete: function(data){
              $("#create_anon_searches .button").show();
              $("#tw_search_spinner").hide();
              if(data.responseText == 'false'){
                $(".error_bubble").html("That search doesn't have enough results to make a good frint :( Try something that might be more popular.").show();
              }else{
                $("#create_anon_searches").submit();
              }
            }
          }
        }

      },

      errorPlacement: function(error, element) {
        error.appendTo(".error_bubble");
        $("#create_anon_searches .button").show();
        $("#tw_search_spinner").hide();
      }

		});
	}


	$("#logout").click( function(){
		window.location.href = '/clearsessions';
	});

	$("#sfWebDebug").click(function(){});

  $('input[name="TW_search"]').each(function(){
    if(this.value==''){
      this.value='Twitter Search';
      $(this).css('color', 'grey');
    }
  });

  $('input[name="TW_search"]').focus(function(){
    if(this.value=='Twitter Search'){
      this.value='';
      $(this).css('color', 'black');
    }
  });

  $('input[name="TW_search"]').blur(function(){
    if(this.value==''){
      this.value='Twitter Search';
      $(this).css('color', 'grey');
    }
  });

});

function mojax(extra){

	if( extra == 'rebuild' ){
		$('#frint_loaded').hide();
		$('#frint_pre').fadeIn();
	}
	mojax_request = true;
  block_interaction();
	mojax_check();
}

function mojax_check(){
	$.getJSON('/statuses/' + rid + '.json', function(data){
		
		//if(subDomain == 'dev.') console.log(data);
		
		if(data == null){
		  data.error = false;
		  data.status = "Missed a beat!";
		}

		//alert( data.permalink + " :: " + data.error);
		if(data.error){
			mojax_request = 'none';
			$("#frint_loading").html("There was a problem building your frint :( Please tell us about it. <br /> " + data.error);
			_gaq.push(['_trackEvent', 'Frint', 'Render Error', data.fid]);
		}else if(data.status == 'complete'){
			mojax_request = 'none';

			frint_url = 'http://' + subDomain + 'frintr.com/' + data.permalink;
			//Hide the user's unfrinted image
			$("#frint_pre").hide();
			//Place the image on the page
			$("#frint_loaded").html('<a href="' + data.permalink + '_standard.jpg" class="colorbox"><img src="' + data.permalink + '_small.jpg" /></a>');
			$(".colorbox").colorbox();
			//Update the fid
			$(".product").each( function(index){
				var id = $(this).attr('id').split('_');
				var type = id[0];
				$(this).attr('id', type + '_' + data.fid);
			});

			//And this is what it's ALL ABOUT! Fade in their frint :)
			$("#frint_loaded").fadeIn();
      unblock_interaction();
			_gaq.push(['_trackEvent', 'Frint', 'Rendered', data.fid]);

			$("#post_render_stuff").fadeIn();
			$("#consent").show();
			$("#consent a").attr('id', data.fid);
			
			$("#permalink_tip").attr('href', frint_url).html(frint_url).parent().show();

			fb_feed_form_attachment = {
				'name': fb_feed_form_name,
				'href': 'http://' + subDomain + 'frintr.com/' + data.permalink,
				'description': fb_feed_form_description,
				'media': [{
					'type': 'image',
					'src': 'http://' + subDomain + 'frintr.com/' + data.permalink + '_small.jpg',
					'href': frint_url
				}]
			};

			mojax_complete(data);
		}else{
			//Do a crude check to see if the App server has run into an unreportable problem.
			//Maybe it's just slow!
			if(previous_status == data.status){
				watch_for_crash++;
			}else{
				watch_for_crash = 0;
			}
			if(watch_for_crash > 60){
				$("#frint_loading").html('No progress in a while, maybe the Frint builder has crashed :( <br /> We\'ll keep trying though!');
				//mojax_request = 'abort';
			}else{
				//update the status onscreen
				$("#frint_loading").html(data.status);
			}

			if(watch_for_crash > 100){
				$("#frint_loading").html('It\'s taken too long. Aborting. Please tell us about it.');
        $('#contactable').trigger('click');
				mojax_request = 'abort';
			}

			if(mojax_request != 'abort') setTimeout(mojax_check, 750);
			previous_status = data.status;
		};
	});
}

function mojax_complete(data){
	$.post('/frint/modis_completed', data, function(returned_data){
		//just saving the frint in the DB and updating the active_frint id in the session
		//maybe should check for success though tom?
	});
}

function addToCart(element){

	//$(element).next('.shop_loading').show();

	var product = $(element).attr('id');

	$.get('/cart/add/id/' + product, function(data){

		//$(element).next('.shop_loading').hide();

		if(data.error){
			//
		}else{
      //console.log(data);
      window.location.href = '/shop';
			//Place the AJAX result in the menu
			//$('#cart_menu').html(data);

			//Hide the "Add to cart" button
			//$(element).hide();
			//Show the "Checkout" and "Remove from cart" buttons
			//$(element).next('.checkout').show().highlightFade({color:'green', speed:2000, end:'white'});
		}
	});
}

function doToCheckout(element, action){

  var product = $(element).parents('.item').attr('id');
  var fid = product.split('_');
  fid = fid[1];

  //Show the Ajax Loader
  $('.ajax_holder' + fid).hide('fast', function(){
    $('.ajaxing' + fid).show();
  });

  $.get('/cart/' + action + '/id/' + product, function(data){

    if(data.error){
      //
    }else{
      //Place the AJAX result in the menu
      $('#cart_menu').html(data);
      updateCheckout();
    }
  });
}

function orderStatusCheck(){
  $.get('/sfPaymentPayPal/orderstatus/oid/' + oid, function(data_raw){
    if(data_raw == 'confirmed'){
      window.location.href = window.location.href;
    }else{
      setTimeout(orderStatusCheck, 1000);
    }
  });

}

function openPopup(URL){
  window.open(URL, 'Connect', popupSpecs(900, 600));
}

function popupSpecs(width, height){
  return  "width="	+ width +
	  ",height="	+ height +
	  ",left="	+ ((screen.width - width) / 2) +
	  ",top="       + ((screen.height - height) / 2);
}

function updateCheckout(){
  $.get('/shop', function(data){
    if(data.error){
      //
    }else{
      //Place the AJAX result in the page
      $('#content').html(data);
      $(".colorbox").colorbox();
      bindings_for_checkout();
    }
  });
}

function bindings_for_checkout(){

//   $("#fb_email_perm").click( function(){
// 		FB.login(
// 			function(response) {
// 				if (response) {
// 					result = response.perms.split(',');
// 					if(result[0] == 'email'){
// 						$("#email").attr('value', 'FB').attr('class', '');
// 						$("#email_confirm").attr('value', 'FB').attr('class', '');
// 						$("#contact").hide();
// 						$("#contact_thankyou").show().highlightFade({color:'green', speed:2000, end:'white'});
//
// 					}
// 				}
// 			},
// 			{perms: 'email'}
// 		);
//     return false;
//   });

  if($().validate){
    //PAYPAL FORM
    $("form[name=gateway_form]").validate({

      submitHandler: function(form){

        $("#buy_spinner").show();
        $("#buy_button").hide();
        //Submit the address and stuff first
        $.post("/shop/order", $("form[name=address_form]").serialize(), function(data){
          //Update the Paypal form with the order ID
          //alert(data);
          //if(subDomain == 'dev') data = Math.floor(Math.random() * 1000000);
          $("input[name=invoice]").attr('value', data);

          var returnURL = $("form[name=gateway_form] input[name=return]").attr('value');
          $("form[name=gateway_form] input[name=return]").attr('value', returnURL + '/oid/' + data);

          //The actual submission to PayPal
          document.forms["gateway_form"].submit(); //use native submit() to prevent recursion!
        });
      }

    });
  }
}

fileInputs = function() {
  var $this = $(this),
      $val = $this.val(),
      valArray = $val.split('\\'),
      newVal = valArray[valArray.length-1],
      $button = $this.siblings('a'),
      $fakeFile = $this.siblings('.file-holder');
  if(newVal !== '') {
    $button.text('');
    if($fakeFile.length === 0) {
      $button.after('<a class="file-holder">' + newVal + '</a>');
    } else {
      $fakeFile.text(newVal);
    }
  }
}

function fb_frint_feed_form(){
  var message = 'I made a mosaic from all my Facebook friends!';

  var action_links = [{
    'text':'Build your own',
    'href':'http://www.frintr.com/'
  }];

  FB.ui({
		method: 'stream.publish',
		message: message,
		attachment: fb_feed_form_attachment,
		action_links: action_links
	},
	function(response) {
		if (response && response.post_id) {
			$('#fb_feed_form').fadeOut();
		} else {

		}
	});

	$('body').scrollTop(20);
  return false;
}

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function mojax_abort(){
	if(mojax_request != 'none'){
		//alert("aborting mojax");
		mojax_request = 'abort';
		$('#frint_loading').html('Frint build stopped ...');
    unblock_interaction();
	}
}

function timestamp(){
  return Math.round((new Date()).getTime() / 1000);
}

function block_interaction(){ 
  $(".interactionBlocker").show();
  $(".interactionBlocker").parent().css('opacity', 0.5);
}

function unblock_interaction(){
  $(".interactionBlocker").hide();
  $(".interactionBlocker").parent().css('opacity', 1);
}
