$(document).ready(function(){
	try {
		//makeWin ("/popup/index","popup","300","300");
	} catch(e) {
		alert('팝업이 차단되어 있습니다.');
	}
	$('#special_img').mouseover(function(){
		$('#special_sale').show();
		$('#best_seller').hide();
	});
	
	$('#best_img').mouseover(function(){
		$('#best_seller').show();
		$('#special_sale').hide();
	});
	
	
	/**
	 * 메인 중앙 상품 탭
	 */
	$('.tab_menu img').click(function(){
		
		var idx = $('.tab_menu img').index(this);
		
		$('.tab_menu img').each(function(){
			
			$(this).attr('src', $(this).attr('src').replace('_on.gif', '.gif'));
			
		});
		
		$(this).attr('src', $(this).attr('src').replace('.gif', '_on.gif'));
		
		if ($(this).attr('id') == 'best_seller_button') {
			$('#new_arrival_div').hide();
			$('#best_seller_div').show();
		} else {
			$('#best_seller_div').hide();
			$('#new_arrival_div').show();
		}
		
	})
	.mouseover(function(){
		$(this).css('cursor', 'hand');
	});
	
	
	/**
	 * 섬네일, 리스트 목록 제어
	 */
	$('.list_box_change_button').click(function(){

		if ($(this).attr('id') == 'list_box_thumb') {
			$('.list_box_sum02').show();
			$('.list_box_sum03').hide();
			
			$(this).attr('src', './application/views/welcome/chemlocus/images/pdbtn_sum_on.gif');
			$('#list_box_list').attr('src', './application/views/welcome/chemlocus/images/pdbtn_list.gif');
			
		} else {
			$('.list_box_sum02').hide();
			$('.list_box_sum03').show();
			
			$('#list_box_thumb').attr('src', './application/views/welcome/chemlocus/images/pdbtn_sum.gif');
			$(this).attr('src', './application/views/welcome/chemlocus/images/pdbtn_list_on.gif');
		}
		
		
	})
	.mouseover(function(){
		$(this).css('cursor', 'hand');
	});	
	
	
	/**
	 * 공지사항 FAQ 탭 메뉴
	 */
	$('.main_table_menu').mouseover(function(index){
		
		var idx = $('.main_table_menu').index(this);
		
		$('.main_table_menu').each(function(){
			
			$(this).attr('src', $(this).attr('src').replace('_on.gif', '.gif'));
			
		});
			
		$(this).attr('src', $(this).attr('src').replace('.gif', '_on.gif'));
		
		if (idx == 0) {
			$('#more-button').attr('href', '/notice');
		} else if (idx == 1) {
			$('#more-button').attr('href', '/customer/faq');
		}
		
		$('.main_newslist').hide();
		$('.main_newslist').eq(idx).show();
		
	});
	
	/**
	 * 포토뉴스 관련
	 */
	$('.small_photo').mouseover(function(){
		$('.big_image').attr('src', $(this).attr('src'));
		$('.big_url').attr('href', '/news/view/'+$(this).attr('title'));
		$('.big_url_html').html(newsTitle[$(this).attr('id')])
		photoIndex = $('.small_photo').index(this);
	});
	
	$('.photoNews').mouseover( function() {
		clearInterval(init);  
	}).mouseout( function() {
		init = setInterval(fn_InitPhotoNews, 3000);
	});
	
	init = setInterval(fn_InitPhotoNews, 3000);
	
	
	/**
	 * 주간 뉴스 관련
	 */
	$('.weeklyNewsButton').click(function(){
		newsIndex = $('.weeklyNewsButton').index(this) - 1;
		fn_newsTab();
	});
	
	$('.weeklyNewsArea').mouseover(function(){
		clearInterval(initNews); 
	}).mouseout(function(){
		initNews = setInterval(fn_newsTab, 3000);
	});
	
	initNews = setInterval(fn_newsTab, 3000);
	
	$('.non_news').hover(
		function()
		{
			$('.news_content_layer').hide();
			// 변수 선업
			var newsId;
			var top;
			var left;

			newsId = $(this).attr('id');
			
			if ($.browser.msie == true) {
				if ($.browser.version == '6.0') {
					top		= $(this).offset().top - 160;
					left	= 215
				} else if ($.browser.version == '7.0') {
					top		= $(this).offset().top - 155;
					left	= 215;
				} else {
					top		= $(this).offset().top - 160;
					left	= 215;
				}
			} else {
				top		= $(this).offset().top - 160;
				left	= 215;
			}
			
			if ($('#content_'+$(this).attr('id')).size() > 0) {
				$('#content_'+$(this).attr('id')).css({'top':top,'left':left}).show();
			} else {
				//alert('버전 : '+$.browser.version+'\n\n상단 : '+$(this)[0].offsetTop+'\n\n좌측 : '+$(this)[0].offsetLeft);
				
				$.ajax({
					url : '/welcome/getNewsContent/'+newsId,
					type : 'post', 
					dataType : 'json',
					async : false,
					success : function(resp)
					{
						var div = '<div id="content_'+newsId+'" class="news_content_layer"><div class="inner_content_layer">'+resp.content+'</div></div>';
	
						$('#contentBody').append(div);
						$('#content_'+newsId).css({'top':top,'left':left}).show();
					}
				});
			}
			
		},
		function()
		{
			$('.news_content_layer').hide();
		}
	);
	
});

var photoIndex = 0;
function fn_InitPhotoNews() {
	photoIndex ++;
	if (photoIndex > 4) photoIndex = 0;
	$('.small_photo').eq(photoIndex).triggerHandler('mouseover');
}

var newsIndex = 0;
function fn_newsTab()
{
	try {
		newsIndex++;
		if (newsIndex > 6) newsIndex = 0;
		$('.newsTab>ul>li>a>img').each(function(){
			$(this).attr('src', $(this).attr('src').replace('_on.gif', '_off.gif'));
		});
		
		$('.newsTab>ul>li>a>img').eq(newsIndex).attr('src', ($('.newsTab>ul>li>a>img').eq(newsIndex).attr('src')).replace('_off.gif', '_on.gif'));
		$('.newsTabBox div').hide().eq(newsIndex).show();
		//$('.newsTabBox div').eq(idx).show();
	} catch (e) {
		
	}
	
}



// 레이어 팝업 관련

// 브라우저 버전별 체크
var ns4=document.layers
var ie4=document.all
var ns6=document.getElementById&&!document.all

// 넷스케이프 계열의 낮은 버전 브라우저를 위한....
var dragswitch=0;
var nsx;
var nsy;
var nstemp;

function drag_dropns(name){
	if (!ns4)
		return;
	temp=eval(name);
	temp.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);
	temp.onmousedown=gons;
	temp.onmousemove=dragns;
	temp.onmouseup=stopns;
}

function gons(e){
	temp.captureEvents(Event.MOUSEMOVE);
	nsx=e.x;
	nsy=e.y;
}

function dragns(e){
	if (dragswitch==1){
		temp.moveBy(e.x-nsx,e.y-nsy);
		return false;
	}
}

function stopns(){
	temp.releaseEvents(Event.MOUSEMOVE);
}
// 넷스케이프 계열 낮은 버전 브라우저를 위한.... 끝


// 크로스브라우저의 높은 버전을 위한 변수 정의
var crossobj;
var tempx;
var tempy;
var offsetx;
var offsety;

// 마우스 드래그에 의한 레이어 움직임 통제
function drag_drop(e){
	if (ie4&&dragapproved){
		crossobj.style.left=tempx+event.clientX-offsetx;
		// 움직인레이어의 왼쪽  = 원래위치 + 현재마우스위치 - 눌렀을당시 마우스위치  즉 원래레이어위치에서 마우스가 움직인만큼만 더해라
		crossobj.style.top=tempy+event.clientY-offsety;
		return false;
	} else if (ns6&&dragapproved) {
		crossobj.style.left=tempx+e.clientX-offsetx+"px";
		crossobj.style.top=tempy+e.clientY-offsety+"px";
		return false;
	}
}


//크로스브라우징을 위해 각 변수가 정의
function initializedrag(e, num){
	// 크로스브라우징을 위한 오브젝트 선택 getElementById를 쓸것인지 all.아이디명을 쓸건인지
	crossobj=document.getElementById("popup_"+num);

	// 이벤트가 일어난 오브젝트 선택
	var firedobj=ns6? e.target : event.srcElement;

	// 브라우저별 최상위 오브젝트 이름과 DTD 정의에 따라 body, documentElement의 차이
	var topelement=ns6? "html" : document.compatMode && document.compatMode!="BackCompat"? "documentElement" : "body";

	// while 과 if 문은 어떤 효용이 있는지 잘 모르겠다. 팝업을 움직이는데는 꼭 필요하지는 않다.
	// while문 전체와 if의 조건을 제거해도 효과에 이상은 없다
	while (firedobj.tagName!=topelement.toUpperCase() && firedobj.id!="dragbar"){
		firedobj=ns6? firedobj.parentNode : firedobj.parentElement;
	}

	if (firedobj.id=="dragbar"){
		offsetx=ie4? event.clientX : e.clientX;
		offsety=ie4? event.clientY : e.clientY;
		tempx=parseInt(crossobj.style.left);
		tempy=parseInt(crossobj.style.top);

		dragapproved=true;
		document.onmousemove=drag_drop;
	}
}

// 문서어디에서 마우스를 떼도 더이상 드레그 되지 않도록
document.onmouseup=new Function("dragapproved=false");
	
	

/**
 * 팝업띄우기
 * @param popup_id
 * @param width
 * @param height
 * @param top_position
 * @param left_position
 * @return
 */

function openPopup(popup_id, width, height, top_position, left_position) {
	//var ck_popup = ReadCookie( 'popup_check_'+popup_id );
	var ck_popup = $.cookie('popup_check_'+popup_id);
	
	//임시로 쿠키제거
	//$.cookie('popup_check_'+popup_id, null);
	
	if ( ck_popup == 1 ) return;
	fn_Popup("/popup/index/"+popup_id, 'openPopup'+popup_id, width, height, 0, left_position, top_position);
}

var number = 0;
function mycarousel_itemLoadCallback(carousel, state)
{
    // Since we get all URLs in one file, we simply add all items
    // at once and set the size accordingly.
    if (state != 'init')
        return;
    
	var data = {
			'np' : number
	};
	
    $.post('/welcome/pointitem', data, function(data) {
        mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
    },'json');
};

function mycarousel_itemAddCallback(carousel, first, last, data)
{
    // Simply add all items at once and set the size accordingly.
    var items = (data.pointStr).split('|//|');
    
    $('#point-prod li').remove();
    for (i = 0; i < items.length; i++) {
        carousel.add(i+1, items[i]);
    }

    carousel.size(items.length);
    $('.point-items li p').css('display','block');
};

/**
 * 
 */
function fn_numberTofpoint(n)
{
	number = n
	$('#point-prod').jcarousel({
		itemLoadCallback: mycarousel_itemLoadCallback
    });
}


// 레이어 팝업관련
function popClose(popNo){
	$('#popup_'+popNo).hide();
}

function setCookie(popNo) {
	var expire = new Date();
    var popNo;
	expire.setDate(expire.getDate() + 1 );
	document.cookie = "popup_check_"+popNo+"=1; expires=" + expire.toGMTString()+ "; path=/";
}

function closeWin(popNo) {
	   var popNo;
	   setCookie(popNo);;
	   $('#popup_'+popNo).hide();
}


/**
 * 메인 상품 prev next 버튼
 */
function fn_mainViewPrevNext(type)
{
		
	var _thisDivId		= '';
	var _thisDivInnerId	= '';
	
	$('.list_box_wrap').each(function(){

		if ($(this).css('display') != 'none') {
			_thisDivId = $(this).attr('id');
		}
		
	});

	$('#'+_thisDivId+' .list_box_sum_detail').each(function(){
		
		if ($(this).css('display') != 'none') {
			_thisDivInnerId = $(this).attr('id'); 
		}
	});

	var page = $('#'+_thisDivInnerId+' input[type=hidden]').val();

	$.post('/welcome/mainProductTable', 'this_page='+page+'&location='+_thisDivInnerId+'&type='+type, function(resp){

		$('#'+_thisDivInnerId).html(resp);	
		
	}, 'html');
		
}


/**
 * 
 * @return
 */
function fn_viewPointLayer(type)
{
	if (type == 'open') {
		$('.main_point').show();	
	} else if (type == 'close') {
		$('.main_point').hide();
	}
}

/**
 * 메일링 신청 레이어폼
 * @return
 */
function fn_mailing()
{
	if ($('.mailing').css('display') == 'none') {
		$('.mailing').css('top', '10px');
		$('.mailing').show();
		$('#mailing_company').focus();
	} else {
		$('.mailing').hide();
		$('#mailing_form input[type=text]').val('').css('background-color', '#FFF');
		
	}
}

/**
 * 메일링 폼 서브밋
 * @return
 */
function fn_getMailing()
{
	if ($('.interest:checked').size() == 0) {
		alert('관심분야를 최소 한 개 이상 선택해주세요.');
		return;
	}
	if(!$('#mailing_form .required').validation(op_language)) return;
	
	var data = $('#mailing_form').serializeArray();
	
	$.post('/welcome/addMailing', data, function(resp){
		if (resp.result == true) {
			alert('메일링이 신청되었습니다.');
			$('.mailing').hide();
			$('#mailing_form input[type=text]').val('').css('background-color', '#FFF');
		} else {
			alert('메일링 신청에 실패하였습니다.');
		}
	}, 'json');
	
}


/**
 * 뉴스 내용 가져오기
 * @param newsId
 * @return
 */
function fn_getNewsContent(newsId)
{
	$('#test').html('<img src="/application/views/layout/chemlocus/images/main/ajax_loader.gif" />');
	$('#test').show();
	$.post('/welcome/getNewsContent/'+newsId, '', function(resp){
		if (resp.result == 'true') {
			$('#test').html(resp.content);
		} else {
			$('#test').html('에러발생');
		}
	}, 'json');
}

