
/**
* Config
*/

var cfg = new Object();

cfg["template"] = "ts24";


/**
* Init
*/

$(function() {

  if ($("#search_quickie").val() == '') {
    $("#search_quickie").defaultvalue($("#search_quickie").attr('title'));
  }

  $('a.facebox').click(function() {
    var page = $(this).attr('href');
    var dialog = $("<div id='shop_dialog'></div>").insertAfter('#footer');
    $(dialog).dialog({
      resizable: false,
      modal: true,
      width: 750,
      height: 450,
      title: $(this).attr('title'),
      open: function(event, ui) {
       $(dialog).load(page);
      },
      close: function() {
        $(dialog).remove();
      }
    });
    return false;
  });

  //all hover and click logic for buttons
	$(".btn-widget:not(.ui-state-disabled)")
	.hover(
		function(){
			$(this).addClass("ui-state-hover");
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	);

  $('a.list_slider').click(function() {
    $("ul#" + $(this).attr('rel')).slideToggle('fast', function ($list_slider) {
	    if ($(this).css('display')=='block') {
        $(this).next().children(':first').hide();
        $(this).next().children(':last').show();
	    } else {
	      $(this).next().children(':first').show();
        $(this).next().children(':last').hide();
	    }
    });
    return false;
  });

  $('#search_vehicles').tabs({
	  show: function(ui) {
	    if ($('.ui-tabs-selected').hasClass('first-selected')) {
        $('#search_list').show();
	    } else {
	      $('#search_list').hide();
	    }
    }
	});
	$('#search_box_selection .button').hide();

  $("input[name='ak']").click(function(){
    $.getJSON('/'+ $(this).val(), {}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].value + '">' + j[i].name + '<\/option>';
      }
      $("select#vehicle_maker").html(options);
      $("select#vehicle_model").attr("disabled","disabled");
      $("select#vehicle_type").attr("disabled","disabled");
    })
  });

  $("select#vehicle_maker").change(function(){
    $.getJSON('/'+ $("input[name='ak']:checked").val() + ',' + $(this).val(), {}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].value + '">' + j[i].name + '<\/option>';
      }
      $("select#vehicle_model").html(options);
      $("select#vehicle_model").removeAttr('disabled');
      $("select#vehicle_type").attr("disabled","disabled");
    })
  });

  $("select#vehicle_model").change(function(){
    $.getJSON('/'+ $("input[name='ak']:checked").val() + ',' + $("select#vehicle_maker").val() + ',' + $(this).val(), {}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].value + '">' + j[i].name + '<\/option>';
      }
      $("select#vehicle_type").html(options);
      $("select#vehicle_type").removeAttr('disabled');
    })
  });

  $("select#vehicle_type").change(function(){
    self.location.href="/" + $("input[name='ak']:checked").val() + ',' + $("select#vehicle_maker").val() + ',' + $("select#vehicle_model").val() + ',' + $("select#vehicle_type").val();
  });

});

/**
* Part
*/
function viewPart()
{
  part_tabs = $('.parts_tabs').tabs();

	$("#part_images_big").click(function(){
	  return openPartImage($(this).attr('href'));
	});
	$("#part_images_more").click(function(){
	  return openPartImage($(this).attr('href'));
	});
	$(".part_images_thumb").click(function(){
	  return openPartImage($(this).attr('href'));
	});

  $(".part_images_thumb").mouseover(function(){

    $("#part_images_big").attr("href", $(this).attr("href"));
    $("#part_images_big>img").attr("src", $(this).children().attr("longdesc"));

    $(".part_images_thumb").children().attr("class", "");
    $(this).children().attr("class", "active");
  });

  loadRecommend();
  loadAddReview();
  loadAddReviewComment();
}

function openPartImage(href)
{
  window.open(href, 'PartsImages', 'width=700,height=600,resizable=1,scrollbars=1,toolbar=1,status=1');
	return false;
}


/**
* Recommend
*/
function loadRecommend()
{
  $('a.recommend').click(function() {

    var page = $(this).attr('href');
    var dialog = $("<div id='shop_dialog'></div>").insertAfter('div#footer');

    $(dialog).dialog({
      resizable: false,
      modal: true,
      width: 600,
      height: 300,
      title: $(this).attr('title'),
      open: function(event, ui) {

       $(dialog).load(page, function () {

         $("#recommend_form").validate({
          rules: {
            email: {
      				required: true,
      				email: true
      			},
      			to_email: {
      				required: true,
      				email: true
      			}
          },
          messages: {
            email: "Geben Sie bitte eine gültige eMail-Adresse ein",
            to_email: "Geben Sie bitte eine gültige eMail-Adresse ein"
          },
          submitHandler: function(form) {
            $.post($(form).attr("action"), $(form).serialize(), function (responseText) {
              $("#recommend_form").hide();
              $("#recommend_success").show();
            });
      		},
          errorLabelContainer: "#recommend_error",
          wrapper: "p"
         });

         $("#recommend_close").click(function () {
           $(dialog).remove();
           return false;
         });
       });
      },
      close: function() {
        $(dialog).remove();
      }
/*      ,
      buttons: {
        "Schließen": function() { $(this).dialog("close"); },
        "Absenden": function() {
        }
      }
*/
    });
    return false;
  });
}


/**
* Reviews
*/
function loadAddReview()
{
  $(".reviews-add").click(function() {

    $("#reviews_add").load( $(this).attr('href'), function() {

      if (!$.fn.rating) {
       $.getScript("/templates/" + cfg.template + "/javascript/rating/jquery.rating.pack.js");
      }

      part_tabs.tabs('select', part_tabs.tabs( 'length' ) - 1);

      if ($("#product_reviews_write>input[name=type]").val() == "question") {
        var msg_text = "Frage";
      } else {
        var msg_text = "Meinung";
      }

      $("#product_reviews_write").validate({
        rules: {
          rating: {
    				required: true
    			},
    			review: {
    				required: true,
    				minlength: 10
    			}
        },
        messages: {
          rating: "Bitte vergeben Sie 1 bis 5 Sterne.",
          review: {
    				required: "Geben Sie bitte Ihre " + msg_text + " ein",
    				minlength: "Ihre " + msg_text + " muss mindesten 10 Zeichen enthalten"
    			}
        },
        highlight: function(element, errorClass) {
           $(element).addClass(errorClass);
        },
        unhighlight: function(element, errorClass) {
           $(element).removeClass(errorClass);
        },
        errorLabelContainer: "#reviews_error",
        wrapper: "li"
    	});

      $("#reviews_add").show();
      $("#reviews_list").hide();
    });

    return false;
  });
}

function loadAddReviewComment()
{
  $(".review_write_comment").click(function() {
    var review_id = $(this).attr('id').split('_');
    review_id = review_id[3];

    $("#review_comment_" + review_id).toggle();

    $("#review_comment_form_" + review_id).validate({
      rules: {
  			comment: {
  				required: true,
  				minlength: 10
  			}
      },
      messages: {
        comment: {
  				required: "Bitte geben Sie ein Kommentar ein",
  				minlength: "Ihr Kommentar muss mindesten 10 Zeichen enthalten"
  			}
      }
  	});

    return false;
  });
}

function review_delete(link)
{
  var review_id = $(link).attr('id').split('_');

  $("#reviews_delete-dialog").dialog({
		bgiframe: true,
		resizable: false,
		autoOpen: false,
		height:140,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		}
	});
  $('#reviews_delete-dialog').dialog('option', 'buttons', {
    "Nein": function() { $(this).dialog("close"); },
    "Ja": function() {
      $("#reviews_edit_result").load( $(link).attr('href') + '&confirm=1' );

      $(this).dialog("close");
      $("#review_" + review_id[2]).fadeOut('slow', function() {
        $("#review_" + review_id[2]).remove();
        $("#reviews_edit_result").fadeIn(function() {
          setTimeout( function() {
             $("#reviews_edit_result").fadeOut("fast");
          }, 5000);
        });
      });
    }
  });
  $('#reviews_delete-dialog').dialog('option', 'title', $(link).attr('title'));
  $('#reviews_delete-dialog').dialog('open');

  return false;
}


/**
* Wishlist
*/
function wishlist_delete(link)
{
  var wish_id = $(link).attr('id').split('_');

  $("#dialog").dialog({
		bgiframe: true,
		resizable: false,
		autoOpen: false,
		height:140,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		}
	});

  $('#dialog').dialog('option', 'buttons', {
    "Nein": function() { $(this).dialog("close"); },
    "Ja": function() {
      $("#result").load( $(link).attr('href') + '&confirm=1' );

      $(this).dialog("close");
      $("#wish_" + wish_id[2]).fadeOut('slow', function() {
        $("#wish_" + wish_id[2]).remove();
        $("#result").fadeIn(function() {
          setTimeout( function() {
             $("#result").fadeOut("fast");
          }, 5000);
        });
      });
    }
  });
  $('#dialog').dialog('open');

  return false;
}


/**
* Tools
*/
function installSearchEngine(url) {
  if (window.external && ("AddSearchProvider" in window.external)) {
    window.external.AddSearchProvider(url);
  } else {
    alert("Das funktioniert mit Ihrem Browser leider nicht.");
  }
}

// Default Value
// http://plugins.jquery.com/project/defaultvalue

(function($) {

	$.fn.defaultvalue = function() {

		// Scope
		var elements = this;
		var args = arguments;
		var c = 0;

		return(
			elements.each(function() {

				// Default values within scope
				var el = $(this);
				var def = args[c++];

				el.val(def).focus(function() {
					if(el.val() == def) {
						el.val("");
					}
					el.blur(function() {
						if(el.val() == "") {
							el.val(def);
						}
					});
				});

			})
		);
	}
})(jQuery)

/*
 * jQuery Timer Plugin
 * http://www.evanbot.com/article/jquery-timer-plugin/23
 *
 * @version      1.0
 * @copyright    2009 Evan Byrne (http://www.evanbot.com)
 */

jQuery.timer = function(time,func,callback){
	var a = {timer:setTimeout(func,time),callback:null}
	if(typeof(callback) == 'function'){a.callback = callback;}
	return a;
};

jQuery.clearTimer = function(a){
	clearTimeout(a.timer);
	if(typeof(a.callback) == 'function'){a.callback();};
	return this;
};
