// Show advanced search
function show_advanced(type) {
	if (type == 'red') {
		if ($('div.search-ap-simple_off').length > 0) {
			$('div.search-ap-simple_off .advanced-block').removeClass('hideme');
			$('div.search-ap-simple_off .options, div.search-ap-simple_off').removeClass('off_1');
			$('.search-ap-simple_off').removeClass('search-ap-simple_off').addClass('search-ap-simple');

				$('div.search-ap-simple .advanced-block').hide();
				$('div.search-ap-simple .advanced-block').fadeIn('slow');	
		} else {
			$('.search-ap-simple').removeClass('search-ap-simple').addClass('search-ap-simple_off');
			$('div.search-ap-simple_off .options, div.search-ap-simple_off').addClass('off_1');
			$('div.search-ap-simple_off .advanced-block').addClass('hideme');
			$('div.search-ap-simple_off .advanced-block').hide();
		}
	} else {
		if ($('div.search-ld-simple_off').length > 0) {
			$('div.search-ld-simple_off .advanced-block').removeClass('hideme');
			$('div.search-ld-simple_off .options, div.search-ld-simple_off').removeClass('off_1');
			$('.search-ld-simple_off').removeClass('search-ld-simple_off').addClass('search-ld-simple');

				$('div.search-ld-simple .advanced-block').hide();
				$('div.search-ld-simple .advanced-block').fadeIn('slow');	
		} else {
			$('.search-ld-simple').removeClass('search-ld-simple').addClass('search-ld-simple_off');
			$('div.search-ld-simple_off .options, div.search-ld-simple_off').addClass('off_1');
			$('div.search-ld-simple_off .advanced-block').addClass('hideme');
			$('div.search-ld-simple_off .advanced-block').hide();
		}
	}
}



function stopDefault(e) {
	if (e && e.preventDefault) e.preventDefault();
	else e.returnValue = false;
}

function getRadioValue(radioObj) {
	if(!radioObj) return "";
	if(radioObj.length == undefined)
		if(radioObj.checked)
			return "/("+radioObj.name+")/"+radioObj.value;
		else
			return "";
	for(var i = 0; i < radioObj.length; i++) {
		if(radioObj[i].checked) {
			return "/("+radioObj[i].name+")/"+radioObj[i].value;
		}
	}
	return "";
}

function getTextValue(textObj,tname) {
	if(!textObj) return "";
	if(textObj.value.length > 0)
		return "/("+tname+")/"+textObj.value;
	return "";
}

function searchComments(term, t, p, url) {
  function processTable(data) {
    jQuery('table#comments-results tbody').empty();
    jQuery(data).find('tr').each(function(){
      jQuery('table#comments-results tbody').append(this);
    });
    return false;
  }
  jQuery.ajax({
    async: false,
    dataType: 'html',
    data: 'term=' + term + '&t=' + t + '&p=' + p,
    url: url,
    success: function (data, textStatus) {processTable(data);},
    error: function (XMLHttpRequest, textStatus, errorThrown) {
    	//alert(textStatus);
    }
  });
}

function setTM(mode) {
  setTypingMode(mode);
  jQuery.cookie('VietTypingMode', mode, {path: '/', expires:16384});
  return true;
}

function ajaxGetRelated( url, context, link )
{
  jQuery(link).addClass('showall-ajax-loading'); 
  jQuery.ajax({
    url: url,
    dataType: 'html',
    success: function(data, textStatus){
      jQuery(context).append(data);
      jQuery(link).remove();
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      jQuery(link).removeClass('showall-ajax-loading');
    },
    complete: function(XMLHttpRequest, textStatus){
    }
  });
}

//////
jQuery(document).ready(function() {
//////

var VietTypingMode = parseInt(jQuery.cookie('VietTypingMode'));
VietTypingMode = (VietTypingMode >= 0 && VietTypingMode <= 2 ? VietTypingMode : 1);
setTM(VietTypingMode);
jQuery('#langmode input#lm-' + VietTypingMode).attr('checked', true);

jQuery('input[type="text"], textarea').bind('keyup', function(e){initTyper(jQuery(this).get(0));});

jQuery('.tabbox').tabs();

jQuery('table.results tbody tr').hover(
  function() {jQuery(this).addClass('hover');},
  function() {jQuery(this).removeClass('hover');}
).click(function(){
  jQuery(this).find('a:eq(0)').each(function(){
    if (jQuery(this).attr('target')=='_blank') {
      //console.log(jQuery(this).attr('href'));
      window.open(jQuery(this).attr('href'), '');
      //return false;
    }
    else {
      //console.log('2');
      window.location.href=jQuery(this).attr('href');
    }
  });
});

jQuery('a.icon-help-open').click(function(){
  var help = jQuery(this).attr('rel');
  jQuery('.help-window').not('#' + help).fadeOut('fast');
  jQuery('#' + help).fadeIn('fast');
});

jQuery('a.icon-help-close').click(function(){
  jQuery(this).parent('div').parent('div').fadeOut('fast');
});

function jsonSuggestSelect_callback(item) {
  //alert(JSON.stringify(item));
  return false;
}

jQuery('.search-ap-simple-hook .text, .search-ap-advanced #term').jsonSuggest(
  function(text, wildCard, caseSensitive, notCharacter) {
    var JSONData = '';
    /*var success = false;*/
    function processJSONData(data) {
      for (var i in data.facet_counts.facet_fields.ezf_df_text) {
        if (i%2 == 0) {
          if (i != 0) JSONData += ',';
          JSONData += '{"text":"' + data.facet_counts.facet_fields.ezf_df_text[i] + '"}';
        }
        success = true;
      }
    }
    jQuery.ajax({
      async: false,
      dataType: 'json',
      data: 'p=' + 'ap' + '&keyword=' + text,
      url: '/ezsuggest/searchsolr',
      success: function (data, textStatus) {processJSONData(data);},
      error: function (XMLHttpRequest, textStatus, errorThrown) {
      	//alert(textStatus);
      }
    });
    
    /*var timer;
    function checkSuccess() {if (!success) timer = setTimeout("checkSuccess();",100);}
    clearTimeout(timer);

    checkSuccess();*/
    
    return JSON.parse('[' + JSONData + ']');
  }, {ajaxResults:true, maxResults:9, minCharacters:2, onSelect:jsonSuggestSelect_callback}
);

jQuery('.search-ld-simple-hook .text, .search-ld-advanced #term').jsonSuggest(
  function(text, wildCard, caseSensitive, notCharacter) {
    var JSONData = '';
    /*var success = false;*/
    function processJSONData(data) {
      for (var i in data.facet_counts.facet_fields.ezf_df_text) {
        if (i%2 == 0) {
          if (i != 0) JSONData += ',';
          JSONData += '{"text":"' + data.facet_counts.facet_fields.ezf_df_text[i] + '"}';
        }
        success = true;
      }
    }
    jQuery.ajax({
      async: false,
      dataType: 'json',
      data: 'p=' + 'ld' + '&keyword=' + text,
      url: '/ezsuggest/searchsolr',
      success: function (data, textStatus) {processJSONData(data);},
      error: function (XMLHttpRequest, textStatus, errorThrown) {
      	//alert(textStatus);
      }
    });
    
    /*var timer;
    function checkSuccess() {if (!success) timer = setTimeout("checkSuccess();",100);}
    clearTimeout(timer);

    checkSuccess();*/
    
    return JSON.parse('[' + JSONData + ']');
  }, {ajaxResults:true, maxResults:9, minCharacters:2, onSelect:jsonSuggestSelect_callback}
);

// tree

jQuery.ui.dynatree.nodedatadefaults["icon"] = false;
jQuery("#tree").dynatree({
  title: "Lazy loading sample",
  rootVisible: false,
  persist: false,
  fx: { height: "toggle", duration: 1 },
  // initAjax is hard to fake, so we pass the children as object array:
//      initAjax: { .. },
/*  children: [
    {title: "Simple node", key: "1" },
    {title: "Lazy folder", isFolder: true, isLazy: true, key: "2"},
    {title: "Lazy document", isLazy: true, key: "3"}
    ],
*/
  onActivate: function(dtnode) {
    jQuery("#echoActive").text(dtnode.data.title);
    if(dtnode.data.url) window.location.href=dtnode.data.url;
  },
/*
  onExpand: function(flag, dtnode) {
            if( !flag && dtnode.data.isLazy ) // Unload lazy nodes on collapse (so they are reloaded next time)
                dtnode.removeChildren();
  },
*/
  onLazyRead: function(dtnode){

    dtnode.appendAjax({
      url: "eztree/getnodes",
      data: {c:dtnode.data.key}
    });

    // typically we would call something like this:
//              dtnode.appendAjax(
//                  {url: "/getChildrenAsJson",
//                 data: {key: dtnode.data.key,
//                        mode: "funnyMode"
//                          }
//                });
    // ... but in this sample we just simulate the behaviour:
/*    var fakeJsonResult = [
        { title: 'Lazy node 1', isLazy: true },
        { title: 'Simple node 2', select: true }
    ];
    function fakeAjaxResponse() {
      return function() {
        dtnode.append(fakeJsonResult);
        // Remove the 'loading...' status:
        dtnode.setLazyNodeStatus(DTNodeStatus_Ok);
      };
    }*/
    //window.setTimeout(fakeAjaxResponse(), 1500);
  }

});

jQuery('div.class-faq a.faq-question').click(function(){
  jQuery('div.class-faq div.faq-answer').hide();
  jQuery(this).parent().parent().find('div.faq-answer').show();
});

jQuery('td.sq-td').click(function(){
  jQuery('div.sq-full').hide();
  jQuery(this).find('div.sq-full').show();
});


//////
});
//////
