// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

//TODO: fix this to work on onDomReady event ..

/*$(document).ready(function(){
  $("a[class^=paginate_]").each(function(){$(this).attr("href",Utilities.get_page_url($(this).attr("class")));});
});*/
$(document).ready(function(){

  //home page title wrapping w.r.t. 1/2/3 title shown on right top
  if(!$.browser.msie)
    $("#item0 h3:eq(0)").width($("#item0").width()-120);

  //if compare link is clicked.
  if(window.location.href.indexOf("#compare")!=-1) {
    if(window.location.href.indexOf("catalog")==-1){
      $("div#compare-home>a").click();
    } else {
      show_comparison(window.location.hash.replace("#compare-","").split(','));
    }
  }

  // IE style
  if($.browser.msie) {
    //$(".score, .totalscore").css("margin-left","-28px !important");
  }
  Utilities.safariFixes();
  // IE 6.0 fix for the sliding thing
  $("#allfeatures li").css("width",$("#allfeatures").width());
  $("#snippetBox li").css("width",$("#snippetBox").width());
  // scores greater than 9.7 are not displayed properly :(
  if($.browser.msie && parseInt($.browser.version)<7) {
    $(".barrange").each(function(i,a){
      var r = parseInt($(a).css("width").replace("%",""));
      if(r>97) $(a).css("width","97%");
    });
  }
    //$(".barrange").each(function(i,a){if($(a).width()>97) $(a).width(97);});

	//On item page, show the first feature as the selected feature by default
	var path=location.pathname;
	path=path.substring(path.lastIndexOf('/')+1,path.length);
	var node=$("div#allfeatures>ul>li>div:contains('" + path + "')");
	if(node.attr("id") != null) {
		node.addClass("selectedfeature");
		$("div#top5>ul>li:contains('" + path + "')").addClass("selectedfeature");
	} else {
		$("div#top5>ul>li:eq(0)").addClass("selectedfeature");
		$("div#allfeatures>ul>li:eq(0)>div:eq(0)").addClass("selectedfeature");		
	}
});

// new home page tabbing functionality
$('.hometabbing>a').click(function(){
	$("div[id^=item_]").hide();
	var attr = $(this).attr("class").split(' ')[0].replace("paginate_","");
	$("div#item_"+attr).show();
	$(".hometabbing>a").removeClass("current");
	$(this).addClass("current");
});

// following 2 behaviors add the more/less functionality for features. defaultly 8 are shown, on click on more all should be shown
$("p#morefeatures>a").click(function(){
  $(this.parentNode).hide();
  $("div.showhide[@class*='features']").slideDown("fast");
  $('#lessfeatures').show();
  always_show_we_all_features(true);
});

$("p#lessfeatures>a").click(function(){
  $(this.parentNode).hide();
  $("div.showhide[@class*='features']").slideUp("fast");
  $('#morefeatures').show();
  always_show_we_all_features(false);
});

function always_show_we_all_features(yes_no) {
  $.ajax({
    type: "POST",
    data: {},
    url: "/call/show_all_features?id=" + (yes_no?"1":"0"),
    success: function(msg) {}
  });
}

// tabbing on main page for top 3 items of a product - 1-2-3
$("div[@id^=item_tab]>a").click(function() {
  var num = $(this.parentNode)[0].id.replace(/item_tab/, "");
  $("div#item0,#item1,#item2").hide();//css("display", "none");
  $("div#item"+num).show();//css("display", "block");
  $("div#compare-home-layer").hide();$("div#compare-home").show();
	$("#morecameras").css("padding-top","20px");
	$(".camalt1 a, .camalt2 a, .camalt3 a").removeClass("moreleft");
  if(!$.browser.msie)
    $("#item"+num+" h3:eq(0)").width($("#item"+num).width()-120);
});

// comparison implementation for home page
$("div#compare-home>a").click(function(){
	var idlist = $("#compare-home-layer>p").html().replace(" ","","g");
	$.ajax({
      type: "GET",
      url: "/" + Utilities.get_product_name() + "/compare?home=1&ids="+idlist+window.location.search.replace("?","&"),
	  beforeSend: function() {
			$("#compare-home-layer").before("<div id='compare-home-loading' style='height:"+$("#item1").height()+"px;padding:30px 0 0 30px;font-size:1.3em;'>Loading..</div>");
			$("div#item1,div#item2,div#item0").hide();
	  },
	  success: function(msg) {
			Utilities.do_flash_work(true);
			$("#compare-home-layer>p").hide();$("#compare-home").hide();
			$("#compare-home-loading").remove();
			$("#compare-home-layer").show();
			$("#morecameras").css("padding-top","0px");
			$(".camalt1 a, .camalt2 a, .camalt3 a").addClass("moreleft");
		}
  });
});

// CATALOG PAGE :
// comparison box implementation
$("label[for^=compare] a").click(function(){
  var a=jQuery(this).parent().prev();
  a.click();
});

$("input[type='checkbox'][name^=compare]").click(function(){
  add_delete_comparison_box(this.name.split('_')[1], this.parentNode.parentNode);
});

$("#comparisons span.remove a").click(delete_from_comp_box_and_select);
function delete_from_comp_box_and_select() {
  var id = $(this).parent().attr("id").split('_')[1];
  var elem = $("input[name=compare_"+id+"]");
  if(elem) elem.attr("checked", (elem.attr("checked")==null? "true":""));
  add_delete_comparison_box(id, this.parentNode.parentNode.parentNode.parentNode,true);
}

// 2nd argument tells if loading button should be displayed below the compare check box
function add_delete_comparison_box(elem, custom_loading, display_success_message_at_top){
  // show loading
  var id = elem;
  var current_count_in_comp_box=0;
  $.ajax({
    type: "GET",
    url: "/" + Utilities.get_product_name() + "/update_compare",
    data: "id="+id,//+"&add="+this.checked,
    beforeSend: function() {
			current_count_in_comp_box = $(".comp_box_ele").length;$("#success_flash").remove();
			if (!custom_loading) {
				Utilities.show_spinner();
			} else {
				Utilities.show_custom_spinner(custom_loading);
			}
		},
    success: function(msg) {
      $("#comparisons div").remove();
	  	Utilities.hide_spinner();
      $("#success_flash").remove();
      $("#comparisons h3").after(msg);
      var new_length = $(".comp_box_ele").length;

			var temp_elem = $("#header2");
			if(custom_loading && !display_success_message_at_top) {temp_elem = $(custom_loading); }
			temp_elem.append("<div id='success_flash'><div>Product has been " + ((current_count_in_comp_box < new_length)?"added to":"deleted from ") + (new_length>0? " <a href='#comparisons'>Comparison Box</a>" : "Comparison Box") + "</div></div>");
      
			if(msg.length==0) {$("#comparisons").css("display","none");return;}
      $("#comparisons").css("display","block");
      $("#comparisons span.remove a").click(delete_from_comp_box_and_select);
    }
  });
}

// click on "more details" should open the product detail tab
$("#moredetails").click(function(){
  $("div[class^=scour_]").css("display","none");
  $("p[id^=slightnav_]").css("display","none");
  
  $("div.scour_2").css("display","block");
  $("p#slightnav_2").css("display","");
});

// tabbing on item page for reviews/details/price-comp
$("p[id^=slightnav_]>a").click(function(){
  var val = $(this).text();
  //FIXME: I am big BUG and very poor way of doing stuff, nakul sucks
  var mapping = {"Specification":2,"Reviews":1,"Price Comparison":3};
  $("div[class^=scour_]").css("display","none");
  $("p[id^=slightnav_]").css("display","none");
  
  $("div.scour_"+mapping[val]).css("display","block");
  //OPTIMIZE: once price loaded, new ajax request should be forbidden
  var p = window.location.pathname;
  var pn = Utilities.get_product_name();
  var pidd = p.indexOf("/",p.indexOf(pn)+pn.length+1);
  var productname = p.substring(p.indexOf(pn)+pn.length+1,(pidd==-1?p.length:pidd));
  if(mapping[val]==3 && $("div.scour_"+mapping[val]).text().replace("\n","","g").indexOf("Loading..")!=-1) {
    $.ajax({
      type: "GET",
      url: "/" + pn + "/pricing",
      //FIXME: am a bug in pricing
      data: "id="+productname,//window.location.path.substring(window.location.path),
      //dataType: "json",
      success: function(msg) {
        $('#priceloading').remove();
        $("div.scour_"+mapping[val]).append(msg);
      }
    });
  }
  $("p#slightnav_"+mapping[val]).css("display","");
});

// show all features
$("#top5>p>a").click(function(){$('#top5').css("display","none");$("#allfeatures").css("display","block");});
// show only top+bottom ones
$("#allfeatures>div.back-top-features>a").click(function(){$('#top5').css("display","block");$("#allfeatures").css("display","none");});
// also, sort us by buzz
$("#allfeatures>div.sort-by-buzz>a").click(function(){
	var node = this;
	var selectedfeature = $("div.selectedfeature").attr("id");
	$.ajax({
		type: "GET",
		url: "/" + Utilities.get_product_name() + "/sort_features",
		data: "id="+$(this).attr("id")+"&by="+$(this).html().toLowerCase().replace("sort by ",""),
		beforeSend: function() {var h = $("div#allfeatures").height();$("div#allfeatures>ul").html("<div style='height:"+(h-50)+"px;font-size:1.2em;'>Loading..<div>");},
		success: function(msg) {
			$("div#allfeatures>ul").html(msg);
			$("#leftcolumn a:contains('Why?')").each(function(i,a) {update_snippet_box(a);});
			var node = "#allfeatures>div.sort-by-buzz>a";
			if($(node).html().indexOf("Buzz")!=-1) $(node).html("Sort by Score");
			else $(node).html("Sort by Buzz");
			$("li#"+selectedfeature).addClass("selectedfeature");
			$("div.ab").each(function(i,a){if($(a).attr("id")==selectedfeature) $(a).addClass("selectedfeature");});
      Utilities.safariFixes();
			//$("div#allfeatures>ul>li:eq(0)>div:eq(0)").addClass("selectedfeature");
		}
	});
});

// change snippet values
$("#leftcolumn a:contains('Why?')").each(function(i,a) {update_snippet_box(a);});
//$("#leftcolumn a:contains('Why?')").each(function(i) {
function update_snippet_box(node) {
  $(node).attr("href","javascript:void(0);");
  $(node).click(function(){
	var id=$(node).parent().attr("id");
    $.ajax({
      type: "GET",
      url: "/" + Utilities.get_product_name() + "/show_snippets",
      data: "id="+id,
      beforeSend: function(){
        /* if user was at details tab .. then direct him to review tab again... */
        $("div[class^=scour_]").css("display","none");
        $("p[id^=slightnav_]").css("display","none");
        
        $("div.scour_1").css("display","block");
        $("p#slightnav_1").css("display","");

        $("div.scour_1").html("<div style='position:relative;text-align:center;font-size:2em;'>Loading...</div>");
      },//parent().attr("id"));return false;},
      success: function(msg) {
        $("div.scour_1").html(msg);
        $("div#snippetBox").slideView("#prevnext");
        // IE 6.0 fix for the sliding thing
        $("#snippetBox li").css("width",$("#snippetBox").width());
        $("#snippetwhatsthis >a").click(snippetwhatsthiscallback);

		$("#leftcolumn a:contains('Why?')").each(function(i,a){$(a).parent().removeClass("selectedfeature");});
		$("li#"+id).addClass("selectedfeature");
		$("div.ab").each(function(i,a){if($(a).attr("id")==id) $(a).addClass("selectedfeature");});
		//$("div#"+id).addClass("selectedfeature");
      }
    });
  });
}

// show product comparison
$("#comparisons a:last").click(function(){
  var idlist = [];
  $("#comparisons span.remove").each(function(i,a){idlist.push($(a).attr("id").replace("remove_",""));});
  show_comparison(idlist);
});
function show_comparison(idlist){
    if (idlist.length<2) {$("#success_flash").remove();$("#header2").append("<div id='success_flash'><div>Atleast 2 products must be compared</div></div>");return false;}
    $.ajax({
      type: "GET",
      url: "/" + Utilities.get_product_name() + "/compare?ids="+idlist.join(",")+window.location.search.replace("?","&"),
      //data: "id="+$(this).parent().attr("id"),
      beforeSend: function(){
        $("#container").prepend("<div id='comp' style='display:block;'><p id=\"comphead\">Compare " + Utilities.get_product_name() + "s <span><a href=\"javascript:void(0);\">X</a></span></p><div style='position:relative;text-align:center;font-size:2em;'>Loading...</div></div>");
        $("#comphead a").click(function(){$("#comp").remove();});
        index_hash= window.location.href.indexOf('#');
        if(index_hash==-1) window.location.href += "#compare-"+idlist.join(",");
        else window.location.href = window.location.href.substring(0,index_hash)+"#compare-"+idlist.join(",");
        var title=document.title;
        document.title = title.substring(0,title.indexOf("'"))+" > Comparison";
      },
      success: function(msg) {
        $("#comp").html(msg.replace(/^<div id="comp">/i,"").replace(/<\/div>$/i,""));
        if($.browser.msie) {
          $("#comp")[0].innerHTML = msg.replace(/^<div id="comp">/i,"").replace(/<\/div> *$/i,"");
        }
        //$("#comp").innerHTML = msg.replace(/^<div id="comp">/i,"").replace(/<\/div> *$/i,"");
        //$("#container").prepend(msg);
        $("#comphead a").click(function(){
          $("#comp").remove();
          window.location.hash="";
          var title=document.title;
          document.title = title.substring(0,title.lastIndexOf(">")-1)+"'s Catalog";
          //ie6 show the drop down boxes ..
          if($.browser.msie && parseInt($.browser.version)<7) {
            $("select").css("visibility","visible");
          }
        });
        if(idlist.length>=4) $("#comp").css("overflow","scroll");
        $("#comp").css("display","block");
		Utilities.do_flash_work();
      }
    });
    return false;
}

// Feedback box
$("#navigation li:eq(4)>a").click(function(){
  if ($("#feedback").css("display")=="none") {
    $.ajax({
      type: "GET",
      url: "/call/show_feedback_box",
      success: function(msg) {
        $("#feedback").html(msg);
        $("#success_flash").remove();
        $("#feedsubmit").click(feedbackRecurse);
        $("#feedback p>span>a").click(function(){$("#feedback").css("display","none");});
        $("div[@id=item_tab1]>a").click();
        $("#feedback").slideDown();
      }
    });
  }else { 
    $("#feedback").slideUp();
  }
});

function feedbackRecurse() {
  $.ajax({
    type: "POST",
    data: "feedbackername="+$("input[name=feedbackername]").val()+"&feedbacker="+$("textarea[name=feedbacker]").val(),
    url: "/call/submit_feedback",
    success: function(msg) {
      $("#feedback").html(msg);
      $("#feedsubmit").click(feedbackRecurse);
      $("#feedback p>span>a").click(function(){$("#feedback").slideUp();});
    }
  });
  return false;
}


//What's this in snippet box
$("#snippetwhatsthis >a").click(snippetwhatsthiscallback);
function snippetwhatsthiscallback(){
  if ($("#item_snippet_whatsthis").css("display")=="none") {
    $.ajax({
      type: "GET",
      url: "/call/item_snippet_whatsthis",
      success: function(msg) {
        $("#item_snippet_whatsthis").html(msg);
        $("#item_snippet_whatsthis p>span>a").click(function(){$("#item_snippet_whatsthis").css("display","none");});
        $("#item_snippet_whatsthis").slideDown();
      }
    });
  }else { 
    $("#item_snippet_whatsthis").slideUp();
  }
}

// what are all these features about?
$(".attention a").click(function(){
  if ($("#features_whatsthis").css("display")=="none") {
    $.ajax({
      type: "GET",
      url: "/" + Utilities.get_product_name() + "/features_whatsthis",
      success: function(msg) {
        $("#features_whatsthis").html(msg);
        $("#features_whatsthis p>span>a").click(function(){$("#features_whatsthis").css("display","none");});
        $("#features_whatsthis").slideDown();
      }
    });
  }else { 
    $("#features_whatsthis").slideUp();
  }
});


// add_this bookmark button
$("#bookmark").click(function(){
  addthis_url = location.href;
  addthis_title = document.title;
  return addthis_click(this);
});

var Utilities = {
  get_page_url:function(classval) {
    var page = classval.split('_')[1];
    var str = window.location.search;
    if(str=="") {return window.location.pathname+"?page="+page;}
    else {
      if(str.indexOf("page")==-1) {
        return window.location.pathname + window.location.search + "&page="+page;
      } else {
        return window.location.pathname + window.location.search.replace(/page=[0-9]+/,"page="+page);
      }
    }
  },

  get_product_name: function() {
    var str = window.location.pathname;
    str = str.substring(1,str.length);
		var string_end = str.indexOf('/');
		if (string_end == -1) string_end = str.length;
    var name = str.substring(0,string_end);
    if (name=="") name="cameras";
    return name;
  },

  get_session_id: function() {
    var id = undefined;
    $.ajax({
      type: "GET",
      async: false,
      url: "/call/get_session_id",
      success: function(msg) {id=msg;}
    });
    return id;
  },

  show_spinner: function() {$("body").append("<div style=\"position:fixed;top:100px;right:40px;background-color:#FAD163;\" id='spinner'>Loading..</div>");},
  hide_spinner: function() {$("#spinner").remove();},

	show_custom_spinner: function(elem) {
		$(elem).append("<div style=\"background-color:#FAD163;margin:0 auto;padding:5px 10px;width:100%;\" id='spinner'>Loading..</div>")
	},

  safariFixes: function() {
    if($.browser.safari) {
      $("div.barback").css("margin","0px");
      $(".scorebuzz .barback").css("margin-top","-23px");
      $("#allfeatures .barback").css("margin-right","110px");
      $("div.barbacktotal").css("margin","0px");
      $(".column2 .barback, #top5 .barback").css("margin-right","80px");
      $(".column1 .barbacktotal").css("margin-right","60px");
      $(".camcat .barback, .camcat .barbacktotal").css("width","95px !important");
    }
  },

  do_flash_work: function(homepage, id_of_element) {
	var height = 500; var margin_top=170; var margin_bottom=50; var y_label=20; var y_legend=50;
	if(homepage) {
		height=370;margin_top=120;margin_bottom=40;y_label=0;y_legend=30;
	}
	/**
	 Full of comparison thing now moved to javascript.
	 Earlier most of it was in partial, but it somehow doesn't works with IE6 :(
	*/
	    var settings = "<settings><decimals_separator>.</decimals_separator><font>Tahoma</font><text_size>12</text_size>"+
	                   "<plot_area><margins><top>" + margin_top + "</top><bottom>" + margin_bottom + "</bottom></margins></plot_area>"+
	                   "<legend><y>" + y_legend + "</y><values><enabled>true</enabled><text>{value}</text></values></legend><background><color>#ffffff</color><alpha>100</alpha></background>" + 
	                   "<labels><label><y>" + y_label + "</y><width>600</width><align>center</align><text><![CDATA[QuarkGraph]]></text><text_color>#797B75</text_color><text_size>15</text_size></label></labels>" + 
	                   "<grid><x><enabled>false</enabled><approx_count>10</approx_count></x></grid>" + 
										 //<y_left><enabled>false</enabled></y_left>
	                   //"<indicator><enabled>false</enabled></indicator>" +
	                   "<scroller><y>150</y><color>#BBBB00</color><bg_color>#000</bg_color></scroller>" +
	                   "<help><balloon><color>#797B75</color><text>Click on checkbox to show/hide graph of corresponding product. Select the area you wish to enlarge.</text><width>265</width></balloon><button><color>#797B75</color></button></help>" +
	                   "<zoom_out_button><x>260</x><y>120</y><alpha>100</alpha></zoom_out_button>"+
										 "<values><x><text_size>12</text_size></x></values>" +
	                   "<strings><no_data>n/a</no_data><error_in_data_file>None of the products has features to compare</error_in_data_file></strings>"+
	                   //"<graphs>" + titles + "</graphs>"+
                     "<connect>true</connect>" +
	                   "</settings>";
	var xml = document.cookie;
	var i = "_quarkshop_session_id";
	var l = xml.indexOf(";",xml.indexOf(i)+2);
	if(l==-1) l=10000;
	xml = xml.substring(xml.indexOf(i)+i.length+1,Math.min(xml.length,l));
	if($.browser.msie && parseInt($.browser.version)<7) {
	  xml = Utilities.get_session_id();
	  if(!homepage) $("select").css("visibility","hidden");
	}
	var data_file = "/images/" + xml + ".xml";
	var so = new SWFObject("/javascripts/amline/amline.swf", "amline", "620", height, "8", "#FFFFFF");
	//so.addVariable("chart_data", data);
	so.addVariable("path", "/javascripts/amline/");
	so.addVariable("data_file", data_file);
	so.addVariable("chart_settings", settings);
	so.addVariable("preloader_color", "#000000");
	so.write("flashcontent"+(id_of_element?id_of_element:""));
  }
};
