(function($){
	$(function(){
		$("#btn_search").bind("click", Event_lotto);
		$("#btn_search").prev().bind("keypress", Keypress);
		var i="blur focus change "+($.browser.mozilla?"paste input":"keyup");
		$("#status").bind(i,status_keyup);
		$(".btn_reply").live("click",btn_reply_click);
		$("#btn_search_address").bind("click",btn_search_address_click);
		$("#btn_item_add").bind("click",btn_item_add_click);
		$("#btn_item_del").live("click",btn_item_del_click);
		$(".item").live("change", function(){ cost_change(); });
		$(".item_cnt").live("change", function(){ cost_change(); });
		$("#send_price_ok").live("change", function(){ cost_change(); });
		$("#btn_show_item_list").live("click",btn_show_item_list_click);
		$("#btn_close_item_list").live("click",btn_close_item_list_click);
		cost_change();
		page_init();
	});

	var z_index = 0;
	btn_show_item_list_click = function(){
		$(this).attr("id","btn_close_item_list");
		var top = $(this).parent().position().top;
		var left = $(this).parent().position().left;
		left = left + 90;
		var org_id = $(this).attr("id");	
		var idx = $(this).closest("ul").attr("id");
		
		var list_content = "";
		var obj_list = JSON.parse($(this).attr("data"));
		var price = 0;
		for (var i = 0;i < obj_list.lists.length; i++){
			if (i > 0){
				var border = " style='border-top:1px solid #cacaca; margin-top:5px; padding-top:5px;'";
			}			

			var item_text = "<p" + border + "> 물품내용 : " + obj_list.lists[i].item + "</p>";
			var size_text = "<p> 사이즈 : " + obj_list.lists[i].size + "</p>";
			var price_text = "<p> 금액 : " + obj_list.lists[i].price + "</p>";
			var cnt_text = "<p> 수량 : " + obj_list.lists[i].item_cnt + "</p>";

			price = price + parseInt(obj_list.lists[i].price) * parseInt(obj_list.lists[i].item_cnt);
			list_content = list_content + item_text + size_text + price_text + cnt_text;
		}

		if (obj_list.send_price_ok == "True" || obj_list.send_price_ok == "1"){
			var send_price_text = "(배송비 +" + $("#send_price").text() + "원)";
			price = price + parseInt($("#send_price").text());
		}
		else{
			var send_price_text = "";
		}

		list_content = list_content + "<p style='padding-top:5px; font-weight:bold;'> 총 금액" + send_price_text + " : " + price + "원</p>";

		$("<div id='list_form_" + idx + "' class='list_form round'>" + list_content + "</div>").appendTo("body");
		$("#list_form_" + idx).css("width","300px").css("border","1px solid #CACACA");
		$("#list_form_" + idx).css("top",top+"px").css("left",left+"px");
		$("#list_form_" + idx).css("padding","5px").css("position","absolute");
		$("#list_form_" + idx).css("cursor","pointer").css("word-wrap","break-word").css("z-index",z_index);
		$("#list_form_" + idx).css("background-color","#fff");
		$("#list_form_" + idx).bind("click", function(){
			$(this).remove();
			$("#" + idx).find("#btn_close_item_list").attr("id","btn_show_item_list");
		});		
		z_index++;
	}

	btn_close_item_list_click = function(){
		$("#list_form_" + $(this).closest("ul").attr("id")).remove();
		$(this).attr("id","btn_show_item_list");
	}

	cost_change = function(){
		var price = 0;
		$(".item").each(function(){
			var obj_value = JSON.parse($(this).val());
			var cnt = $(this).closest("p").find("#item_cnt").val();
			price = price + obj_value.price * cnt;
		})
		if ($("#send_price_ok").val() == "1"){
			price = price + parseInt($("#send_price").text());
		}
		$("#item_price").text(price);
	}

	btn_item_del_click = function(){
		$(this).closest("p").remove();
		cost_change();
		return false;
	}

	btn_item_add_click = function(){		
		var item_form_html = $(this).closest("p").find(".item_form").html();
		var btn_item_del = "<a id='btn_item_del' href=''>삭제</a>";
		$("<p style='padding-bottom:2px'>" + item_form_html + btn_item_del + "</p>").insertAfter($(this).closest("p"));
		cost_change();
	}

	btn_search_address_click = function(){
		winOpen('/searchAddress.html', 'address', 418, 400);
	}


	ajax = function(type,data,url,success,error,complete){
		$.ajax({
			type:type,
			url:url,
			data:data,
			success:success,
			error:error,
			complete:complete
		});
	}		

	btn_reply_click = function(){
		var id = $(this).closest("dl").find("dt a span").html();
		var status = "@" + id + " ";		
		$("#status").attr("value",status).focus();
	}

	status_keyup = function(){
		var len = $("#status").attr("value").length;
		//$("#text_count").html(len);
		if (len > 140){
			//$(this).closest(".writebox").find("#text_count").css("color","red");			
		}
		else{
			//$(this).closest(".writebox").find("#text_count").css("color","");
		}
	}

	loadMoreList = function(more){		
		var idx = $("#idx").attr("value");		
		//$(".event_list").fadeOut(function(){
			new Ajax.Request('/event/eventsub.html',{
				parameters:{
					idx:idx,
					more:more,
					mode:"more"
				},
				onSuccess:function(res){
					$(".event_list").html(res.responseText);	
					//$(".event_list").fadeIn();
				},
				onFailure:function(res){
				}
			});
		//});
	}

	Event_lotto = function(){ 
		var screenname = $("#popup_id").attr("value");
		var idx = $("#idx").attr("value");
		new Ajax.Request('/event/eventsub.html',{
			parameters:{
				idx:idx,
				screenname:screenname,
				mode:"lotto"
			},
			onSuccess:function(res){	
				$("#person").html(res.responseText)
			},
			onFailure:function(res){
				
			}
		});
	}

	Keypress = function(event){
		if (event.which == 13)
		{
			Event_lotto();
		}
	}

	event_apply = function(el){
		if (check_tweet_form_validate() != false){
			var scroll_top = $(window).scrollTop() + 100;
			var left = ($(window).width() - $(".div_user_info").width()) / 2;
			var win_height = $(window).height();
			$(".hidden_layer").css("height",win_height+"px");
			$(".hidden_layer").css("opacity",0.3);
			$(".hidden_layer").show();
			if (template == "confirm_form"){			
				$(".div_user_info_confirm").css({"position":"absolute","top":scroll_top+"px", "left":left, "z-index":10000});
				$(".div_user_info_confirm").fadeIn();			
			}else if (template == "write_form"){
				$(".div_user_info_confirm").hide();
				$(".div_user_info").css({"position":"absolute","top":scroll_top+"px", "left":left, "z-index":10000});
				$(".div_user_info").fadeIn();	
			}		
		}		
	}

	check_tweet_form_validate = function(){
		var el = $(".btn_apply");
		var shorturl = $("#shortUrl").attr("value");
		var screen_name = document.getElementById("screen_name").value;
		var thumb = document.getElementById("thumb").value;
		var id = $("#num").attr("value");
		var status = $(el).closest("div").find("#status").attr("value");		
		var corp = $("#company").html();
			
		if (status == "")
		{
			return false;
		}		

		if ($(el).attr("id") == "event_apply"){
			var mode = "4";
			var t_movie_id = $("#t_movie_id").val();
			var event_idx = $("#idx").val();
			var _data = {
				screen_name:screen_name,
				thumb:thumb,				
				status:status,
				id:id,
				url:shorturl,
				mode:mode,
				corp:corp,
				t_movie_id:t_movie_id,
				event_idx:event_idx
			}
		}
		else if ($(el).attr("id") == "seller"){		
			if ($("#username").val() == ""){
				alert("이름을 입력해주세요");
				$("#username").focus();
				return false;
			}
			if ($("#phonenumber").val() == ""){
				alert("휴대폰번호를 입력해주세요");
				$("#phonenumber").focus();
				return false;
			}
			if ($("#zipcode1").val() == "" || $("#zipcode2").val() == ""){
				alert("우편번호를 입력해주세요");
				winOpen('/searchAddress.html', 'address', 418, 400);
				return false;
			}
			if ($("#address").val() == ""){
				alert("주소를 입력해주세요");
				$("#address").focus();
				return false;
			}
			if ($("#size").val() == ""){
				alert("사이즈를 입력해주세요");
				$("#size").focus();
				return false;
			}
			var mode = "seller";
			var event_idx = $("#idx").val();
			var username = $("#username").val();
			var phonenumber = $("#phonenumber").val();
			var zipcode = 	$("#zipcode1").val() + "-" + $("#zipcode2").val();
			var address = $("#address").val();	
			var send_price_ok = $("#send_price_ok").val();

			var item_array = new Array();
			var size_array = new Array();
			var item_cnt_array = new Array();
			var price_array = new Array();

			$(".item").each(function(){
				var obj_price = JSON.parse($(this).val());
				item_array.push(obj_price.item);
				price_array.push(obj_price.price);
			});

			$(".size").each(function(){
				size_array.push($(this).val());
			});
			$(".item_cnt").each(function(){
				item_cnt_array.push($(this).val());
			});

			var item = {
				"lists" : new Array()			
			}

			for (var i = 0; i < item_array.length; i++){
				var temp = {
					"item":item_array[i],
					"size":size_array[i],
					"item_cnt":item_cnt_array[i],
					"price":price_array[i]
				};
				item.lists.push(temp);
			}		

			item = JSON.stringify(item);	
			//item = "{\"lists\":[{\"item\":\"test\",\"size\":\"size\"}]}";
			
			var more_info = $("#more_info").val();
			var _data = {
				screen_name:screen_name,
				thumb:thumb,				
				status:status,
				id:id,
				url:shorturl,
				mode:mode,
				corp:corp,
				username:username,
				phonenumber:phonenumber,
				event_idx:event_idx,
				zipcode:zipcode,
				address:address,
				item:item,	
				more_info:more_info,
				send_price_ok:send_price_ok
			}			
		}
		else if ($(el).attr("id") == "review_apply"){
			if ($("#movie_rate").val() == "0"){
				alert("평점을 입력해주세요");
				$("#username").focus();
				return false;
			}
			var mode = $(el).attr("id");
			var screen_name = $("#screen_name").val();
			var thumb = $("#thumb").val();
			var status = $("#status").val();
			var id = $("#num").attr("value");
			var shorturl = $("#shortUrl").attr("value");
			var mode = "review_apply";
			var corp = $("#company").html();
			var t_movie_id = $("#t_movie_id").val();
			var event_idx = $("#idx").val();
			var movie_rate = $("#movie_rate").val();
			var _data = {
				screen_name:screen_name,
				thumb:thumb,				
				status:status,
				id:id,
				url:shorturl,
				mode:mode,
				corp:corp,
				t_movie_id:t_movie_id,
				event_idx:event_idx,
				movie_rate:movie_rate
			}
		}
		else if ($(el).attr("id") == "event"){
			var mode = $(el).attr("id");
			var screen_name = $("#screen_name").val();
			var thumb = $("#thumb").val();
			var status = $("#status").val();
			var id = $("#num").attr("value");
			var shorturl = $("#shortUrl").attr("value");
			var mode = "event";
			var corp = $("#company").html();
			var t_movie_id = $("#t_movie_id").val();
			var event_idx = $("#idx").val();
			var _data = {
				screen_name:screen_name,
				thumb:thumb,				
				status:status,
				id:id,
				url:shorturl,
				mode:mode,
				corp:corp,
				t_movie_id:t_movie_id,
				event_idx:event_idx
			}
		}
		else{
			var mode = "1";
			var event_idx = $("#idx").val();
			var _data = {
				screen_name:screen_name,
				thumb:thumb,				
				status:status,
				id:id,
				url:shorturl,
				mode:mode,
				corp:corp,
				event_idx:event_idx
			}
		}
		return _data;
	}

	Event_twitterUpdate = function(){
		var _data = check_tweet_form_validate();

		if (_data != false){
			var el = $(".btn_apply");		

			if (ajax_loading == 1){
				return false;
			}
			ajax_loading = 1;
			
			var parent = $(el).parent();
			$(el).hide(); 
			$(parent).append("<img id='process' src='/img/search/loader3.gif' alt='updating' style='margin:6px 48px 4px 46px; vertical-align:middle;'>");			

			new Ajax.Request('/event/Event_Update.html',{
				parameters:_data,
				onSuccess:function(res){	
					$(el).show(); 
					$(parent).find("#process").remove();				
					$(res.responseText).insertAfter(".event_list .list");	
					if ($(".btn_apply").attr("id") == "seller"){
						$.alertTop("신청하였습니다");
					}else{
						$.alertTop("응모하였습니다");
					}

					if ($(".event_list ul").size() == 1){
						$(".event_list #null").remove();
						$(".event_list ul:first").css("border","0");
					}				
					$("#status").val(default_status);
					ajax_loading = 0;				
				},
				onFailure:function(res){	
					$(el).show(); 
					$(parent).find("#process").remove();
					ajax_loading = 0;
				}
			});				
		}		
	}

	Event_Deltwitter = function(idx, el){
		if (confirm('정말 삭제 하시겠습니까?'))
		{
			var target = $(el).parent().parent().parent().parent().parent();
			$(target).fadeOut();
			new Ajax.Request('/event/Event_twitter_delete.html',{
				parameters:{
					idx:idx,
					mode:"1"
				},
				onSuccess:function(res){	
					var id = $("#num").attr("value");
					target.remove();			
					$(".event_list ul:first").css("border-top","0");
				},
				onFailure:function(res){
					
				}
			}) ;
		}
	}

	Event_Retwit = function(el){		
		var id = $(el).parent().parent().prev().children("a").children("span").html();
		var text = $(el).closest("dl").find(".txt_status").text();
		var status = "RT @" + id + " " + text + " ";		
		$("#status").attr("value",status).focus();
	}

	Event_MyInterest = function(){
		var idx = $("#num").attr("value");
		new Ajax.Request('/event/Event_interest.html',{
			parameters:{	
				idx:idx
			},
			onSuccess:function(res){
				if (res.responseText == "0"){
					alert('이미 등록하였습니다');
				}
				else{
					alert('등록 하였습니다.');				
				}
			},
			onFailure:function(res){				
							
			}
		});		
	}

	Event_search = function(){		
		var m = $("#goods").val();
		var q = $("#q2").attr("value");
		location.href = "/event/index.html?m=" + encodeURI(m) + "&q=" + encodeURI(q);
	}

	Event_Edit = function(idx){
		location.href = "/event/registeration1.html?idx=" + idx + "&mode=edit";
	}

	Event_delete = function(idx){
		new Ajax.Request('/event/Event_delete.html',{
			parameters:{	
				idx:idx
			},
			onSuccess:function(res){
				if (res.responseText == "1"){
					history.back();
				}
				else{
					alert('Fail!!!!!!');				
				}
			},
			onFailure:function(res){				
							
			}
		});		
	}	

	btn_search_address_click = function(){
		var url = "/menu_movie/searchAddress.html";			
		winOpen(url, 'address', 418, 400);
		return false;
	}

	date_change = function(){
		var year = $("#birthday_year").val();
		var month = $("#birthday_month").val();
		var _data = {
			year:year,
			month:month
		}
		var _url = "/event/getDate.html";
		$.ajax({
			type:"post",
			data:_data,
			url:_url,
			success:function(msg){
				$("#birthday_day").html(msg);
				birthday_day_setting();
			}
		});
	}

	birthday_day_setting = function(){
		if (!loaded){
			$("#birthday_day").val(birthday_day);
			loaded = true;
		}			
	}

	input_value_setting = function(){
		if (wire_agency != ""){
			$("#wire_agency").val(wire_agency);
		}	
		if (phone1 != ""){
			$("#phone1").val(phone1);
		}
		if (sex != ""){
			$("#sex").val(sex);
		}		
	}

	email_add_select_change = function(){
		var type = $(this).val();
		if (type == "직접입력"){
			$("#mail2").focus();
		}else if (type == "선택하세요"){
			return false;				
		}else{
			$("#mail2").val($(this).val());
		}
	}

	check_validate = function(){
		var checked1 = $("#agree_1").attr("checked");
		var checked2 = $("#agree_2").attr("checked");

		if ($("#real_user_name").val() == ""){
			alert("이름을 입력해주세요");
			$("#real_user_name").focus();
			return false;
		}else if ($("#birthday_year").val() == "" || $("#birthday_year").val().length < 4){
			alert("생년월일이 잘못 입력되었습니다.");
			$("#birthday_year").focus();
			return false;
		}else if ($("#phone2").val() == ""){
			alert("연락처를 입력해주세요");
			$("#phone2").focus();
			return false;							
		}else if ($("#phone3").val() == ""){
			alert("연락처를 입력해주세요");
			$("#phone3").focus();
			return false;							
		}else if ($("#mail1").val() == ""){
			alert("E-mail을 입력해주세요");
			$("#mail1").focus();
			return false;							
		}else if ($("#mail2").val() == ""){
			alert("E-mail을 입력해주세요");
			$("#mail2").focus();
			return false;						
		}else if ($("#address_num1").val() == "" || $("#address_num2").val() == ""){
			alert("우편번호를 입력해주세요");
			var url = "/menu_movie/searchAddress.html";			
			winOpen(url, 'address', 418, 400);
			return false;							
		}else if ($("#address").val() == ""){
			alert("주소를 입력해주세요");
			$("#address").focus();
			return false;							
		}else if ($("#address_more").val() == ""){
			alert("나머지 주소를 입력해주세요");
			$("#address_more").focus();
			return false;							
		}else if (!checked1){
			alert("이용약관에 동의해주세요");
			return false;
		}else if (!checked2){
			alert("개인정보 수집 및 이용에 동의해주세요");
			return false;
		}else{
			return true;
		}
	}

	btn_write_ok_click = function(){
		if (check_validate()){
			var param = $("form[name=user_info]").serializeArray();
			var _data = {};
			for (var i = 0;i < param.length;i++){
				var name = param[i].name;
				var value = param[i].value;
				_data[name] = value;
			}
			var _url = "event_addinfo_ok.html";
			$.ajax({
				type:"post",
				data:_data,
				url:_url,
				success:function(msg){
					if (msg == "success"){
						Event_twitterUpdate();
						$(".hidden_layer").hide();
						$(".div_user_info_confirm").hide();
						$(".div_user_info").hide();
						template = "confirm_form";

						var real_user_name = $("#real_user_name").val();
						var birthdayNsex = $("#birthday_year").val() + "년 " + $("#birthday_month").val() + "월 " + $("#birthday_day").val() + "일 / " + $("#sex").val();
						var phone_number = "( " + $("#wire_agency").val() + " ) " + $("#phone1").val() + " - " + $("#phone2").val() + " - " + $("#phone3").val();
						var mail = $("#mail1").val() + "@" + $("#mail2").val();
						var address = "(" + $("#address_num1").val() + " - " + $("#address_num2").val() + " ) ";
						address += $("#address").val() + " " + $("#address_more").val();

						$(".real_user_name").html(real_user_name);
						$(".birthdayNsex").html(birthdayNsex);
						$(".phone_number").html(phone_number);
						$(".mail").html(mail);
						$(".address").html(address);
					}
				},
				error:function(){
					alert("형식에 맞지 않은 값이 입력되었습니다.");
				}
			});
		}
		return false;
	}

	btn_userinfo_edit_click = function(){
		template = "write_form";
		event_apply();
		return false;
	}

	hidden_layer_click = function(){
		$(".hidden_layer").hide();
		$(".div_user_info_confirm").hide();
		$(".div_user_info").hide();
	}

	btn_confirm_ok_click = function(){
		Event_twitterUpdate();
		$(".hidden_layer").hide();
		$(".div_user_info_confirm").hide();
		$(".div_user_info").hide();
		return false;
	}

	btn_cancel_click = function(){
		$(".hidden_layer").hide();
		$(".div_user_info_confirm").hide();
		$(".div_user_info").hide();
		return false;
	}

	page_init = function(){
		$(".btn_search_address").bind("click",btn_search_address_click);
		$("#birthday_month").add("#birthday_year").change(date_change);			
		$("#email_add_select").change(email_add_select_change);
		$(".btn_write_ok").bind("click",btn_write_ok_click);
		$(".btn_userinfo_edit").bind("click",btn_userinfo_edit_click);
		$(".btn_confirm_ok").bind("click",btn_confirm_ok_click);
		$(".hidden_layer").bind("click",hidden_layer_click);
		$(".btn_cancel").bind("click",btn_cancel_click);

		date_change();
		input_value_setting();
	}
})(jQuery)
