//console.log graceful degradation
if (typeof console == 'undefined') {  
	var console = {};  
	console.log = function(msg) {  
		return;  
	};  
}

function reloadCaptcha() {
	var random=Math.floor(Math.random()*11)
	document.getElementById('captcha').src = document.getElementById('captcha').src+ '?' + random;
}


function ajaxLink (el,base,args) {
  $(el).attr("href",function() {
		url = $(this).attr("href");
		chunks = url.split("?");
		if (chunks[1]) {
			chunks = "?" + chunks[1] + "&" + args;
		} else {
			chunks = "?" + args;
		}
		ajaxUrl = base + chunks;
		$(this).attr("href", ajaxUrl );
	});
}

function rebound() {
	$("input.select_box,textarea.select_box").focus(function() { $(this).select(); });
	$("a.flag_red").click(function(){
    yes = confirm("Are you sure you want to flag this entry?");
    if (!yes) {
      return false;
    }

		a_id = $(this).attr("id");
		id = a_id.split("_")[1];
		href = $(this).attr("href");
		href = href.split("/");
		$.ajax({
		type: "GET",
		url: "/process/flag/" + href[3] + "/?id=" + id,
		success: function(evt, request, settings) {
			$("a#"+ a_id).before(evt);
			$("a#"+ a_id).remove();
		},
		error: function(msg) {
			alert("Failed: Please contact us with this issue [2].");
		}
		}, a_id);
		return false;
	});
}

$(document).ready(function() { 

  //console.log($("*").size());
  
	var $domain = $("span#domain").text(); //domain	
	var $id_no =  $("span#id_no").text(); //id_no

  // TAG_VIEW PRODUCT HOVER
  var $upid = 0;
  var $pid = 0;

  //$("#global ul li:not(:last)").css({"border-right-width":"1px"});
  // $("#global ul li:last").css({"border-right-width":"0px"});

  $("#container a.fav").click(function(ev){
    $t = $(this);

    //fav product
    $.getJSON($t.attr("href"),null,function(json){
      var notice = $("<div class='notice radius_5'>"+json.msg+"</div>");
      notice.appendTo("#container").hide();
      var nH = notice.height();
      var nW = notice.width();
      
      left  = ev.pageX-(nW/2)+"px";
      top   = ev.pageY-(nH/2)-20+"px";
      
      notice.css({
          "top":top,
          "left":left
        }).show().effect("pulsate", { times: 1 }, 1200).fadeOut(200);

    });
    //change img icon
    $t.find("img").attr("src","/images/save_to_faves_btn_h.gif");
    return false;
  });

  function showPmodal(){
		$t = $(this);
		wrapper = $t.parents("div.tag_prod"); //for tag_prod child hover
		vars = wrapper[0].id.split("-"); // $t over wrapper for tag_prod div
		$pid = vars[1];
		$enc_tag = vars[2];
		if ($pid != $upid) {
			$("#loader").hide().empty();
			$upid = $pid;
			viewport = $(window).width();
			href = "/modal/product/" + $pid + "/" + $enc_tag + "/";
			//pos = $t.position();
			pos = wrapper.position();
			pos.top = pos.top + 128;
			pos.left = pos.left - 37;
      if ($.browser.msie) {
        //avoids heavy black border ugliness
        $("#loader").css(pos).load(href).show();
      } else {
        $("#loader").css(pos).load(href).fadeIn(500);
      }
  	} //check for unique pid
  	//return false;
  }

  function hidePmodal(){
  	$t = $(this);
  	if ($("#loader:visible" && ($pid != $upid))){ // 
  		$("#loader").fadeOut(500);
  	}
  	$upid = $pid = 0;
  }

	//THICKBOX MODAL FOCUS
	function TBfocus() {
		return $("#TB_window input[type=text]:first").focus();
	}
	$("a.thickbox").bind("click",function(){
		setTimeout(TBfocus,1000);
	});
  
  // GLOBAL RULES

  $("input.select_box,textarea.select_box").focus(function() { $(this).select(); });
  $("a.t_tip").Tooltip({showURL: false, left: -25, delay: 0});
  $("a.b_tip").Tooltip({showURL: false, top: -25, left: -25, delay: 0});

	if ($("#flash").size()) {
		$("#flash").animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800);
	}

  $("#search form").submit(function() {
    if ($("input:first").val() == "Looking for a costume?") {
      alert("Please enter a search term and try again.");
      return false;
    } else { return true;}
  });

  $("input.select_box").focus(function() {
    $(this).select();
  });
  
  $("input[type=submit]").addClass("submit");
  $("input[type=password], input[type=text], input[type=file], textarea").addClass("text");
  $("input[type=radio]").addClass("radio");
  $("input[type=checkbox]").addClass("checkbox");
	
	$("input[type=password], input[type=text], textarea, select").focus(function() {
		if (this.className.match(/\bprepopulated\b/)) {
			this.value = '';
		}
		$(this).addClass("focus");
	});
	
	$("input[type=password], input[type=text], textarea, select").blur(function(){
		if ($(this).find(".focus")) {
			$(this).removeClass("focus");
		}
	});
	

  //degrades login/register
	var c_url = document.getElementById("curr_url").innerHTML; //FUCK IE6, FUCK FUCK
	var ec_url = escape(c_url);
	//registerModal("a.register","/modal/register/","width=450&height=460&curr_url="+c_url);
	ajaxLink("a.register","/modal/register/","width=450&height=490&curr_url="+ec_url);
	ajaxLink("a.user_login","/modal/login/","width=300&height=300&curr_url="+ec_url);
	ajaxLink("#submit_idea","/modal/best_costume/","width=400&height=550&modal=true");
	ajaxLink("a.contest_upload","/costume-upload/","modal=1&KeepThis=true&TB_iframe=true&width=550&height=500");
	ajaxLink("a.how_add","/how-to-be/","modal=1&KeepThis=true&TB_iframe=true&width=400&height=500");
	ajaxLink("a.costume_idea","/costume-idea/","modal=1&KeepThis=true&TB_iframe=true&width=550&height=500");
	// ajaxLink("a#how_idea","/how-to-costumes/add/","width=400&height=550&modal=true");


  $("a.close").click(function(){
    $(this).parent().parent().hide();
    return false;
  });

  $("a#toggle_debug").click(function() {
    $("#debug_smarty").toggle();
    return false;
  });

  $("a#toggle_sql").click(function() {
    $("#debug_sql").toggle();
    return false;
  });

	$("#costume_rating div.contest_meta").hover(function() {
		//bug
		$(this).css("cursor","pointer");
		$(this).find("a.cast_your_vote").removeClass("cast_your_vote").addClass("cast_your_vote_h");
		$(this).click(function() {
			clickit = $(this).find("a.cast_your_vote_h").attr("href");
			location.href = clickit;
		});
	}, function() {
		$(this).find("a.cast_your_vote_h").removeClass("cast_your_vote_h").addClass("cast_your_vote");
	});
	
	$("#search_term").autocomplete("/process/search/",{
			minChars: 1,
			selectFirst: false,
			max: 24,
			scrollHeight: 220
		});
		
	// HOW TO / COSTUMES THUMB UP/DOWN VOTE
	$("a.vote_up,a.vote_down").click(function(){
		$t = $(this);
		href = $t.attr("href");
		$.getJSON(href,function(json){
			ht_vote = $t.parents("p.ht-vote");
			dump = ht_vote.find("em");
			span = ht_vote.find("span");
			span.show();dump.hide();
			if (json.dump) {
				span.hide();
				dump.show().html(json.dump).effect("pulsate", { times: 1 }, 1200);
				return false;
			}
			ht_vote.find("b.votes_p").fadeOut(200).html(json.votes_p).fadeIn(400);
			ht_vote.find("b.votes_n").fadeOut(200).html(json.votes_n).fadeIn(400);
		});
		return false;
	});
		
  // POPULAR COSTUME IDEAS body#popular
	if ($("body#popular").size()) {
		$("div.top_product").hover(function() {
			$(this).find("div.num_box").addClass("lime");
		}, function() {
			$(this).find("div.num_box").removeClass("lime");
		});
	}

  // COSTUME CONTEST body#tag_view body#index
  if ($("body#costume_contest,body#costume_rate").size()) {
	
		$(".thumb_up,.thumb_down").click(function(){
			alert("You must rate from 1-10! Click on a number to rate.");
		});
		
		$("form#costume_rating_form input#vote_button").css({
			"position":"absolute",
			"top":"0",
			"right":"9999px"
		});
		// $("form#costume_rating_form input[type=radio]").hide();
		$("form#costume_rating_form input[type=radio]").css({
			"position":"absolute",
			"top":"0",
			"right":"10099px"
		});
		$("form#costume_rating_form label").addClass("contest_selector");
		$("label.contest_selector").hover(function(){ 
			$(this).addClass("contest_selector_h");
		}, function() {
			$(this).removeClass("contest_selector_h");
		});
		
		rebound();
		
		// var container = ("#container");
		var contest_image = $("#contest_image");
		var vote_eid = $("input#vote_eid");
		// var contest_results = $("#contest_results");
		// var contest_content = $("#contest_content");
		// var contest_next = $("#next_up");

		// var costume_rating = $("#costume_rating");

		$("form#costume_rating_form input[type=radio]").live("click",function(){
			form = $(this).parents("form:first");
			data = form.serialize();
			var options = { 
				type: "POST",
				dataType: "json",
				data: data,
				timeout: 30000,
				beforeSend: function(xhr) {
					contest_image.html("").addClass("loading");
					// contest_content.html("").addClass("loading");
				},
				success: function(evt, request, settings) {
					if (evt.results) {
						// console.log(evt.results);
						window.location.href = evt.results+"?finished=1";
						return;
					}
					// console.log(evt);
					vote_eid.val(evt.vote_eid);
					contest_image.html("").removeClass("loading");
					//http://jqueryfordesigners.com/image-loading/
					var img = new Image();
					$(img).load(function () {
						$(this).hide();
						contest_image.removeClass('loading').append(this);
						$(this).fadeIn(200);
						})
						.error(function () {
							alert("image could not be retrieved");
						})
						.attr('src', evt.main).wrap("<center></center>");
					$("#contest_results").hide().html(evt.voted).fadeIn(1000);
					$("#next_up").html(evt.next);
					$("#contest_content").html(evt.ctnt + evt.comments);
					$("span#costume_title").hide().html(evt.nav).fadeIn(1000);
					// console.log(evt);
					rebound();
				},
				error: function(evt, request, settings) {
					// console.log(evt);
				}
			}; 
		
			//console.log(options);
			form.ajaxSubmit(options);
			return false;
		});

  }

  
  // PROFILE body#user_profile
  if ($("body#user_profile").size()) {
    $("a.remove_fav").click(function(){
      $t = $(this);
      url = $(this).attr("href");
      yes = confirm("Are you sure you want to delete");
      if (yes) {
        $.getJSON(url,null,function(json){
          $t.fadeOut(200).text(json.msg).fadeIn(600).addClass("lightY").parent().parent().fadeOut(2000);
        });
        return false;
      }
    });
    
    $("#delete_profile a").click(function() {
      yes = confirm("Are you sure you want to PERMANENTLY delete your profile?");
      if (yes) {
        return true;
      } else {
        return false;
      }
    });
  
    $("a.del_profile_pic").click(function() {
      yes = confirm("Are you sure you want to delete this picture?");
      if (yes) {
        return true;
      } else {
        return false;
      }
    });
  }
  
  // TAG VIEW body#tag_view
  if ($("body#review").size()) {
		$("form#check_product input[type=submit]").hide();
		$("form#check_product input").focus(function(){
			bool = $(this).attr("value");
			if (bool == 1) {
				$("div#yes_go").show();
				$("div#no_go").hide();
			} else {
				$("div#no_go").show();
				$("div#yes_go").hide();
			}
		});
	}
	// LIVE SEARCH body#live_search
	if ($("body#live_search").size()) {
		$("#product_list td").click(function(){
			link = $(this).find("a:first").attr("href");
			window.location.href = link;
		});
		
		$("#product_list td").hover(function(){
			$(this).addClass("lightY")
				.find("a").addClass("knock_out");
		}, function(){
			// $(this).css({"background-color":"blue"});
			$(this).removeClass("lightY")
				.find("a")
				.removeClass("knock_out");
		});
	}

  // TAG VIEW body#tag_view
  if ($("body#tag_view").size()) {
	

		$("#wiki_wrap").hide();
		$("a#expand_wiki").css({'cursor':'pointer'}).click(function(){
			$("#wiki_wrap").slideToggle(300);
			var t = $(this);
			//$(this).hasClass("add") ? $(this).removeClass("add").addClass("delete") : $(this).removeClass("delete").addClass("add");
			if (t.hasClass("add")) {
				t.removeClass("add").addClass("delete");
				t.html(t.html().replace(/Show/ig,"Hide"));
			} else {
				t.removeClass("delete").addClass("add");
				t.html(t.html().replace(/Hide/ig,"Show"));
			}
			// 
			// if ($(this).hasClass("add")) {
			// 	$(this).removeClass("add").addClass("delete");
			// }
			// if ($(this).hasClass("delete")) {
			// 	$(this).removeClass("delete").addClass("add	");
			// }
		});
		// if ($("div#wiki_description.expander").size()) {
		//   // override some default options
		//   $('div.expander').expander({
		//     slicePoint:       200,  // default is 100
		//     // expandText:         '[...]', // default is 'read more...'
		//     // collapseTimer:    5000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
		//     userCollapseText: '&laquo; collapse text'  // default is '[collapse expanded text]'
		//   });
		// }
		
		// $('table.list_format tr').hover(function(){
		// 	var t = $(this);
		// 	t.css({
		// 		"background":"#f1f9fe",
		// 		"cursor":"pointer"
		// 	}).click(function(){
		// 		t.find('a:first').trigger("click");
		// 	});
		// 	}, function(){
		// 		$(this).css({
		// 			"background":"none"
		// 		});
		// 	}
		// );

		// $('.products a[href^=/go]').each(function() {
		// 	// add the current page(c_url) GA tracking code
		// 	$(this).click(function() {
		// 		pageTracker._trackPageview('/outgoing' + c_url);
		// 	});
		// });
		// 
		// $('.products a[id^=email-]').each(function() {
		// 	// add the current page(c_url) GA tracking code
		// 	tag = c_url.split("/")[2];
		// 	$(this).click(function() {
		// 		pageTracker._trackPageview('/goal/tellafriend/'+tag+'-'+this.id);
		// 	});
		// });
		
		$('.products .tag_prod').each(function(){
			tag = c_url.split("/")[2];
			$(this).find('a[href^=/go]').each(function(){
				$(this).click(function() {
					// console.log('/outgoing' + c_url);
					// return false;
					pageTracker._trackPageview('/outgoing' + c_url);
				});
			});
			$(this).find('a[id^=email-]').click(function() {
				// console.log('/goal/tellafriend/'+tag+'-'+this.id);
				// return false;
				pageTracker._trackPageview('/goal/tellafriend/'+tag+'-'+this.id);
			});
			$(this).find('a[href^=http://twitter]').click(function(){
				// console.log('/goal/tweet/'+tag+'-'+this.id);
				// return false;
				pageTracker._trackPageview('/goal/tweet/'+tag+'-'+this.id);
			})
		})



	  // $("#hows .column_2").hover(function(){
	  //   $(this).addClass("knock_out").css({"cursor":"pointer"});
	  //   link = $(this).find("a.ht-title").attr("href");
	  //   $(this).click(function(){window.location.href = link;});
	  // },function(){
	  //       $(this).removeClass("knock_out");
	  // });
	  
	  var tag_modal =  $("span#tag_modal").text(); //lock down modal via db call also
    
    if (parseInt(tag_modal,10)) {
      //preload modal bck
      if ($.browser.msie && $.browser.version < 7) {
        $('<img />').attr('src', '/images/product_hover_bck.gif');
      } else {
        $('<img />').attr('src', '/images/product_hover_bck.png');
      }
      $("div.tag_prod > a").hoverIntent({
        sensitivity: 3,
        interval: 200,
        over: showPmodal,
        timeout: 500,
        out: function(){}
      });
    }
    
    $("body").click(function(e){
      if ($("div#loader:visible")) {
        if ($(e.target).closest("div.product_hover,div.coupon,div.product_modal").length) {
          return;
        } else {
          hidePmodal();
        }
      }
    });

    
		$("a.request_btn").click(function(){
			url = $(this).attr("href");
			append = document.baseURI.split("?");
			if (append[1]) { url = url + "&" + append[1]; }
			$(this).load(url,null,function (responseText, textStatus, XMLHttpRequest) {
				$(this).text(responseText)
					.attr("href","").addClass("disabled_btn")
					.removeClass("request_btn").fadeOut(200).fadeIn(200)
					.bind("click",function(){return false;});
			});
			return false;
		});
	
	
		ajaxLink("a.add_review","/modal/review/","width=400&amp;height=420");
		
/*
		$("div.submit_wrap").css("opacity",".2");
		$("div.submit_object").hover(function() {
			$(this).find("div.submit_wrap").css("opacity","1");
		}, function() {
			$(this).find("div.submit_wrap").css("opacity",".2");
		})

  	$("a#submit_tag_idea").click(function() {
  	  $("#idea_obj_wrap").slideToggle();
  	  $(this).hide();
  	  return false;
  	});
  	$("a#idea_close").click(function() {
  	  $("#idea_obj_wrap").toggle();
  	  $("a#submit_tag_idea").toggle();
  	  return false;
  	});	
    $("a#submit_tag_link").click(function() {
      $("#link_obj_wrap").slideToggle();
      $(this).hide();
      return false;
    });
    $("a#link_close").click(function() {
      $("#link_obj_wrap").toggle();
      $("a#submit_tag_link").toggle();
      return false;
    });  
    $("a#submit_tag_photo").click(function() {
      $("#photo_obj_wrap").slideToggle();
      $(this).hide();
      return false;
    });
    $("a#photo_close").click(function() {
      $("#photo_obj_wrap").toggle();
      $("a#submit_tag_photo").toggle();
      return false;
    });
    $("a#submit_tag_video").click(function() {
      $("#video_obj_wrap").slideToggle();
      $(this).hide();
      return false;
    });
    $("a#video_close").click(function() {
      $("#video_obj_wrap").toggle();
      $("a#submit_tag_video").toggle();
      return false;
    });
*/	

  	// Make all process_types ajax friendly DEPRECATED is_ajax FUNCTION 	
  	// AJAX
    // $("form#link").submit(function() {
    //   ajaxSubmitObject('link');
    //   return false;
    // });
    // $("form#video").submit(function() {
    //   ajaxSubmitObject('video');
    //   return false;
    // });

  	// SHOW product_coupons
  	// $("div.tag_prod a.show_coupons").click(
  	//   function() {
  	//     $(".product_coupons").hide();
  	//         $(".product_reviews").hide();
  	//         $(this).parent().parent().parent().find(".product_coupons").toggle();
  	//     	  return false;
  	//   }
  	// );
	
  	// SHOW product_reviews
  	$("div.tag_prod a.show_reviews").click(
  	  function() {
  	    $(".product_coupons").hide();
        $(".product_reviews").hide();
        $(this).parent().parent().parent().find(".product_reviews").toggle();
    	  return false;
  	  }
  	);
	
  	$("a.add_your_review,a.add_review").click(
  	  function() {
  	    $(".product_coupons").hide();
  	    $(".product_reviews").hide();
  	  }
  	);
	
  	// DEGRADE USER REVIEWS
  	if ($("a.add_review").length) {
    	$("a.add_review").each(function () {
    	  href = $(this).attr("href") + "&modal=1";
        $(this).attr("href",href);
      });
    }
  } //end body#tag_view

}); //end document.ready

function ajaxSubmitObject (type) {
  data = $("form#" + type + " input, form#" + type + " select, form#" + type + " textarea").serialize();
  $.ajax({
    type: "POST",
    url: "/process/object_" + type + "/",
    data: data,
    success: function(msg) {
      $("ul#object_" + type + "s").append(msg);
      //alert( "Data Saved: " + msg );
      $("form#" + type + " input[type=text]").val("");
      $("form#" + type + " #" + type + "_description").val("");
      $("form#" + type + " input[type=text]")[0].focus();
    },
    error: function(msg) {
      alert("Failed: Please contact us with this issue [1].");
    }
  });
}


  
//AUTOCOMPLETE SEARCH
//var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");

//  var datab = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
// $("#kyle").autocomplete(datab);

//AUTOCOMPLETE SEARCH
//var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");

