// global functions
$(function() {
   bind_general();
   bind_my_nav();
   wall_comment();
   classified_category();
   bookmark_category();
   babybook_category();
   dragdrop();
   category_li();
   $(".datepicker").datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: 'dd/mm/yy',
	  yearRange: '1950:c+5' 
    });
   collapse();
   image_rollover();
   show_more();
   auto_highlight();
   //modal_dialog();
   ajax_pagination();
   faq_more();
   video_load();
   subscribe_all();
   delete_comment();
   knowhow_other();
   video_toggle();
});

function video_load(){
    $("#video-latest a").click(function(ev){
	ev.preventDefault();
	$.post(base+'video/show/'+$(this).parents('li').find('.vid_id').val(), {}, function(data){
	    $("#video-player").html(data);
	});
    });
}

function bind_my_nav(){
    $(".my_nav a").click(function(ev) {
	ev.preventDefault();
	if (!$(this).hasClass("active")) {
	    if(!$.browser.msie)
		$("div.ajax_box").block();
	    var target=this;
	    $(target).parents().find('a.active').removeClass();
	    $(target).addClass("active");
	    var link=$(target).attr("href");
	    $.post(link, { command:'ajax' }, function(data){
		$("div.ajax_box").html(data);
		bind_member_script();
		checkSize();
	    });
	}
	return false;
    });
}

function bind_general(){
    var h = window.location.host.toLowerCase();
    $("a[href^='http']:not([href^='http://" + h + "']):not([href^='https://" + h + "']):not([href^='http://www." + h + "']):not([href^='https://www." + h + "'])").attr("target", "_blank");
    $("a.delete").unbind('click').click(function(){
	return confirm('Please click OK if you want to delete this data');
    });
    $(":button, :submit, :reset").mouseover(
	function(){
	    $(this).css({cursor: 'pointer', color: '#0066df'});
	}).mouseout(
	function(){
	    $(this).css({cursor: 'cursor', color: '#333'});
	});
    $(".goback").click(function(ev){
	ev.preventDefault();
	window.history.go(-1);
    });
}

function bind_username_check(){
    var username=$("#chk-username");
    if($(username).length>0){
	$("#r-username, .username_chk").change(function(){
	    $("em.valid").remove();
	});
	$(username).unbind('click').click(function(){
	    var val=$("#r-username, .username_chk").val();
	    if(val.length>0)
		$.post(base+'register/check_username/', {str:val}, function(result){
		    $("em.valid").remove();
		    $("p.error").remove();
		    if(result!=="TRUE")
			toggleError("#r-username, .username_chk", result);
		    else{
			$("em.valid").remove();
			$("#chk-username").parent().after('<em class="valid">The username <strong>'+val+'</strong> is available</em>');
		    }
		});
	});
    }
}

function wall_comment(){
    $('input.comment_show').click(function(){
	$('#wall li.show_text').hide().next('#wall li.show_comment').show();
    }).blur(function(){
	$('#wall li.show_text').show().next('#wall li.show_comment').hide();
    });
}

function updateWidgetData(){
    var items=[];  
    $('.column').each(function(){  
		var columnId=$(this).attr('id');  
		$('.dragbox', this).each(function(i){  
		var collapsed=0;  
		if($(this).find('.body').css('display')=="none")  
			collapsed=1;  
		//Create Item object for current panel  
		var item={  
			id: $(this).attr('id'),  
			collapsed: collapsed,  
			order : i,  
			column: columnId  
		};  
		//Push item object into items array  
		items.push(item);
    });
});  
    //Assign items array to sortorder JSON variable  
    var sortorder={ items: items };  
	//alert('SortOrder: '+$.toJSON(sortorder)); 
    //Pass sortorder variable to server using ajax to save state  
    $.post(base+'welcome/updatePanels/', 'data='+$.toJSON(sortorder), function(response){  
	if(response=="success")  
	/*$("#console").html('<div class="success"><p class="valid-msg">Saved</p></div>').hide().fadeIn(1000);  */
	setTimeout(function(){  
	$('#console').fadeOut(1000);  
	}, 2000);  
    });  
}

function dragdrop(){
    $('.dragbox').each(function(){
		$(this).hover(function(){  
			$(this).find('h2').addClass('collapse');  
		}, function(){  
			$(this).find('h2').removeClass('collapse');  
		})  
		.find('h2').hover(function(){  
			$(this).find('.configure').css('visibility', 'visible');  
		}, function(){  
			$(this).find('.configure').css('visibility', 'hidden');  
		})
		.find('.configure').css('visibility', 'hidden');
        /*if($(this).attr('id')=='item10'){
          alert($(this).find('.header').find('span').length);
          alert($(this).attr('id'));
        }*/
		$(this).find('.header').find('span').click(function(){
        // alert('AA');
			$(this).parent().siblings('.body').toggle();  
			//Save state on change of collapse state of panel  
			updateWidgetData();  
		});
	});

	$('.column').sortable(
	{  
        connectWith: '.column',  
        handle: 'h2',  
        cursor: 'move',  
        placeholder: 'placeholder',  
        forcePlaceholderSize: true,  
        opacity: 0.4,  
        start: function(event, ui){  
			//Firefox, Safari/Chrome fire click event after drag is complete, fix for that  
			//if($.browser.mozilla || $.browser.safari)  
				$(ui.item).find('.dragbox-content').toggle();
		},
		stop: function(event, ui){
			ui.item.css({'top':'0','left':'0'}); //Opera fix  
			updateWidgetData();
		}					  
	}).disableSelection();  
}

function collapse(){
   $("#item11 .header").toggle(function(){
      $("#item11 .body").addClass("hidden");
   }, function () {
      $("#item11 .body").removeClass("hidden");
   });
   
   $("#item10 .header").toggle(function(){
      $("#item10 .body").addClass("hidden");
   }, function () {
      $("#item10 .body").removeClass("hidden");
   });
}

function classified_category(target){
    if(target==undefined)
        target='.classified_category';
    
    $(target).change(function(ev){
		var link=this;
			var i=$(this).siblings().length;
			val=$(this).val();
			
			$(link).nextAll().remove();
		if(val.length>0)
				$.post(base+'classified/ajax_category/', {str:val, total:i}, function(result){
						classified_category($(link).after(result).next());
				});
    });
}

function bookmark_category(target){
    if(target==undefined)
        target='.bookmark_category';
    
    $(target).change(function(ev){
		var link=this;
			var i=$(this).siblings().length;
			val=$(this).val();
			
			$(link).nextAll().remove();
		if(val.length>0)
				$.post(base+'bookmark/ajax_category/', {str:val, total:i}, function(result){
						bookmark_category($(link).after(result).next());
				});
    });
}

function category_li(){
	$('#all_category li').hover(function() {
		$(this).addClass('moustover');
	}, function() {
		$(this).removeClass('moustover');
	});
}

function babybook_category(target){
    if(target==undefined)
        target='.babybook_category';
    
    $(target).change(function(ev){
		var link=this;
			var i=$(this).siblings().length;
			val=$(this).val();
			
			$(link).nextAll().remove();
		if(val.length>0)
				$.post(base+'babybook/ajax_category/', {str:val, total:i}, function(result){
						babybook_category($(link).after(result).next());
				});
    });
}


function image_rollover(){
    $('.rollover').hover(function() {
        $(this).find('.normal').hide();
        $(this).find('.over').show();
    }, function() {
        $(this).find('.normal').show();
        $(this).find('.over').hide();
    });
}


function show_more(){
    $('.show_more').click(function(){
        $(this).parents('.block').find('.more').toggle('fast');
         if($(this).hasClass('up_arrow')){
            $(this).removeClass("up_arrow");
         }else{
            $(this).addClass("up_arrow");
         }
    });
}

function selectAllText(textbox) {
   textbox.focus();
   textbox.select();
}

function  auto_highlight(){
   $('.auto_highlight').click(function() { selectAllText($(this)) });
}

function ajax_pagination(){
$("div.ajax_pagination ul.pagination li a").unbind().click(function(ev){
	  url=ev.target.href;
	  $.post(url,{ action:false }, function(data){
		  $('div.body.ajaxify').html(data);
		  ajax_pagination();
	  });
  	  ev.preventDefault();
	  ajax_pagination();
	  })
}

function requestPermission(url){
    var myPermissions = "publish_stream"; // permissions your app needs
    FB.Connect.showPermissionDialog(myPermissions , function(perms) {
	if(url!=undefined)
	    window.location=url;
	else
	    window.location.reload();
    });
}

function faq_more(){
    $('.faq_more').click(function(){
         var id=$(this).attr('id');
        $(this).parents('.block').find('.faq_'+id).toggle('slow');
    });
}

/*function text_label(){
   $('#form_photo input[type="text"], #form_photo textarea').each(function(){	 
      this.value = $(this).attr('alt');
      $(this).addClass('text-label');
   
      $(this).focus(function(){
          if(this.value == $(this).attr('alt')) {
              this.value = '';
              $(this).removeClass('text-label');
          }
      });
      $(this).blur(function(){
          if(this.value == '') {
              this.value = $(this).attr('alt');
              $(this).addClass('text-label');
          }
      });
   });
}*/
function modal_dialog(){
   $('.dialog').dialog({
      autoOpen: false,
      show: 'blind',
      hide: 'explode'
   });
   $('.message_popup').click(function() {
      $('.dialog').dialog('open');
      return false;
   });
}

function subscribe_all(){
   $("#subscribe_all").click(function(){
      if($(this).val()==1){
         $(".m_subscribe").attr("checked","checked");
         $("#subscribe_all").attr("value","0");
      }
      else{
         $(".m_subscribe").attr("checked","");
         $("#subscribe_all").attr("value","1");
      }
   });
}

function delete_comment(){
   $('.delete-comment').click(function(){
      var data=$(this).attr('id');
      var str=data.split('|');
      var del = this;
      if(confirm('คุณต้องการจะลบข้อมูลนี้ ใช่หรือไม่')){
         $.ajax({
            type: 'POST',
            url: base+str[0]+'/delete_comment',
            data: 'id='+str[1],
            success: function(msg){
                 $(del).parent().parent().remove();
            }
         });
      }
   });
   
   $('.report-comment').click(function(){
      var data=$(this).attr('id');
      var str=data.split('|');
      $.ajax({
         type: 'POST',
         url: base+str[0]+'/report_comment',
         data: 'id='+str[1],
         success: function(msg){
            alert('แจ้งลบ ความเห็น '+str[2]+' เรียบร้อยแล้ว');
         }
      });
   });
   
   $("#username").focus(function(){
		if($("#username").attr('value')=="Username"){
			$("#username").attr('value',"")
		}				  
				
	});
	$("#username").focusout(function(){
		if($("#username").attr('value')==""){
			$("#username").attr('value',"Username")
		}				  
				
	});
	$("#password").focus(function(){
		if($("#password").attr('value')=="Password"){
			$("#password").attr('value',"")
		}				  
				
	});
	$("#password").focusout(function(){
		if($("#password").attr('value')==""){
			$("#password").attr('value',"Password")
		}				  
				
	});
			
}

function knowhow_other(){
    
    $("input[id^='m_know_how']").click(function (){
        if ($("input[id^='m_know_how']:checked").val()=="Other"){
            $("#2_m_know_how").removeClass("hidden");
        }else{
            $("#2_m_know_how").addClass("hidden");
        }
        
    });
    
}

function video_toggle(){
   $('#v_embbed').click(function() {
      $('#v_embbed').removeAttr("readonly").css('background-color','#FFF');
      $('#v_link_embbed').attr('readonly', 'readonly').css('background-color','#CFCFCF');
   });
   
   $('#v_link_embbed').click(function() {
       $('#v_link_embbed').removeAttr("readonly").css('background-color','#FFF');
       $('#v_embbed').attr('readonly', 'readonly').css('background-color','#CFCFCF');

   });   
}
function stf_star(){
	window.open(base+'stf/stf_star',"mywindow","menubar=1,resizable=1,width=500,height=200");
}

function myColor(){
	alert("คุณต้องเป็นสมาชิกเว็บไซต์ MOMchannel.com ก่อนนะคะ");
}

