/**
 * jQuery Plugins for Keyence Download Pages.
 *
 * @author  katsuma@team-lab.com
 * @require  jquery 1.2+
 */
var DD_belatedPNG;
if ($.browser.msie && $.browser.version < 7.0) {
	DD_belatedPNG = {
		ns: 'DD_belatedPNG',
		imgSize: {},
		
		createVmlNameSpace: function() { /* enable VML */
			if (document.namespaces && !document.namespaces[this.ns]) {
			  document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
			}
			if (window.attachEvent) {
				window.attachEvent('onbeforeunload', function() {
					DD_belatedPNG = null;
				});
			}
		},
		
		createVmlStyleSheet: function() { /* style VML, enable behaviors */
			/*
				Just in case lots of other developers have added
				lots of other stylesheets using document.createStyleSheet
				and hit the 31-limit mark, let's not use that method!
				further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
			*/
			var style = document.createElement('style');
			document.documentElement.firstChild.insertBefore(style, document.documentElement.firstChild.firstChild);
			var styleSheet = style.styleSheet;
			styleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
			styleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
			styleSheet.addRule('img.' + this.ns + '_sizeFinder', 'behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;'); /* large negative top value for avoiding vertical scrollbars for large images, suggested by James O'Brien, http://www.thanatopsic.org/hendrik/ */
			this.styleSheet = styleSheet;
		},
		
		readPropertyChange: function() {
			var el = event.srcElement;
			if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
				DD_belatedPNG.applyVML(el);
			}
			if (event.propertyName == 'style.display') {
				var display = (el.currentStyle.display == 'none') ? 'none' : 'block';
				for (var v in el.vml) {
					el.vml[v].shape.style.display = display;
				}
			}
			if (event.propertyName.search('filter') != -1) {
				DD_belatedPNG.vmlOpacity(el);
			}
		},
		
		vmlOpacity: function(el) {
			if (el.currentStyle.filter.search('lpha') != -1) {
				var trans = el.currentStyle.filter;
				trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
				el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
				el.vml.image.fill.opacity = trans; /* complete guesswork */
			}
		},
		
		handlePseudoHover: function(el) {
			setTimeout(function() { /* wouldn't work as intended without setTimeout */
				DD_belatedPNG.applyVML(el);
			}, 1);
		},
		
		/**
		* This is the method to use in a document.
		* @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
		**/
		fix: function(selector) {
			var selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
			for (var i=0; i<selectors.length; i++) {
				this.styleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
			}
		},
		
		applyVML: function(el) {
			el.runtimeStyle.cssText = '';
			this.vmlFill(el);
			this.vmlOffsets(el);
			this.vmlOpacity(el);
			if (el.isImg) {
				this.copyImageBorders(el);
			}
		},
		
		attachHandlers: function(el) {
			var self = this;
			var handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
			if (el.nodeName == 'A') {
				var moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
				for (var a in moreForAs) {
					handlers[a] = moreForAs[a];
				}
			}
			for (var h in handlers) {
				el.attachEvent('on' + h, function() {
					self[handlers[h]](el);
				});
			}
			el.attachEvent('onpropertychange', this.readPropertyChange);
		},
		
		giveLayout: function(el) {
			el.style.zoom = 1;
			if (el.currentStyle.position == 'static') {
				el.style.position = 'relative';
			}
		},
		
		copyImageBorders: function(el) {
			var styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
			for (var s in styles) {
				el.vml.color.shape.style[s] = el.currentStyle[s];
			}
		},
		
		vmlFill: function(el) {
			if (!el.currentStyle) {
				return;
			} else {
				var elStyle = el.currentStyle;
			}
			for (var v in el.vml) {
				el.vml[v].shape.style.zIndex = elStyle.zIndex;
			}
			el.runtimeStyle.backgroundColor = '';
			el.runtimeStyle.backgroundImage = '';
			var noColor = (elStyle.backgroundColor == 'transparent');
			var noImg = true;
			if (elStyle.backgroundImage != 'none' || el.isImg) {
				if (!el.isImg) {
					el.vmlBg = elStyle.backgroundImage;
					el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
				}
				else {
					el.vmlBg = el.src;
				}
				var lib = this;
				if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
					var img = document.createElement('img');
					lib.imgSize[el.vmlBg] = img;
					img.className = lib.ns + '_sizeFinder';
					img.runtimeStyle.cssText = 'behavior:none; position:absolute; left:-10000px; top:-10000px; border:none;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
					img.attachEvent('onload', function() {
						this.width = this.offsetWidth; /* weird cache-busting requirement! */
						this.height = this.offsetHeight;
						lib.vmlOffsets(el);
					});
					img.src = el.vmlBg;
					img.removeAttribute('width');
					img.removeAttribute('height');
					document.body.insertBefore(img, document.body.firstChild);
				}
				el.vml.image.fill.src = el.vmlBg;
				noImg = false;
			}
			el.vml.image.fill.on = !noImg;
			el.vml.image.fill.color = 'none';
			el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
			el.runtimeStyle.backgroundImage = 'none';
			el.runtimeStyle.backgroundColor = 'transparent';
		},
		
		/* IE can't figure out what do when the offsetLeft and the clientLeft add up to 1, and the VML ends up getting fuzzy... so we have to push/enlarge things by 1 pixel and then clip off the excess */
		vmlOffsets: function(el) {
			var thisStyle = el.currentStyle;
			var size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':this.imgSize[el.vmlBg].width, 'h':this.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
			var fudge = (size.L + size.bLW == 1) ? 1 : 0;
			
			/* vml shape, left, top, width, height, origin */
			var makeVisible = function(vml, l, t, w, h, o) {
				vml.coordsize = w+','+h;
				vml.coordorigin = o+','+o;
				vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
				vml.style.width = w + 'px';
				vml.style.height = h + 'px';
				vml.style.left = l + 'px';
				vml.style.top = t + 'px';
			};
			makeVisible(el.vml.color.shape, (size.L + (el.isImg ? 0 : size.bLW)), (size.T + (el.isImg ? 0 : size.bTW)), (size.W-1), (size.H-1), 0);
			makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1);
			
			var bg = {'X':0, 'Y':0};
			var figurePercentage = function(axis, position) {
				var fraction = true;
				switch(position) {
					case 'left':
					case 'top':
						bg[axis] = 0;
						break;
					case 'center':
						bg[axis] = .5;
						break;
					case 'right':
					case 'bottom':
						bg[axis] = 1;
						break;
					default:
						if (position.search('%') != -1) {
							bg[axis] = parseInt(position)*.01;
						}
						else {
							fraction = false;
						}
				}
				var horz = (axis == 'X');
				bg[axis] = Math.ceil(fraction ? ( (size[horz?'W': 'H'] * bg[axis]) - (size[horz?'w': 'h'] * bg[axis]) ) : parseInt(position));
				if (bg[axis] == 0) {
					bg[axis]++;
				}
			};
			for (var b in bg) {
				figurePercentage(b, thisStyle['backgroundPosition'+b]);
			}
			
			el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
			
			var bgR = thisStyle.backgroundRepeat;
			var dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
			var altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
			if (bgR != 'repeat') {
				var c = {'T':(bg.Y), 'R':(bg.X+size.w), 'B':(bg.Y+size.h), 'L':(bg.X)}; /* these are defaults for no-repeat - clips down to the image location */
				if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
					var v = bgR.split('repeat-')[1].toUpperCase();
					c[altC[v].b1] = 1;
					c[altC[v].b2] = size[altC[v].d];
				}
				if (c.B > size.H) {
					c.B = size.H;
				}
				el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
			}
			else {
				el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
			}
		},
		
		fixPng: function(el) {
			el.style.behavior = 'none';
			if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
				return;
			}
			el.isImg = false;
			if (el.nodeName == 'IMG') {
				if(el.src.toLowerCase().search(/\.png$/) != -1) {
					el.isImg = true;
					el.style.visibility = 'hidden';
				}
				else {
					return;
				}
			}
			else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
				return;
			}
			var lib = DD_belatedPNG;
			el.vml = {color: {}, image: {}};
			var els = {shape: {}, fill: {}};
			for (var r in el.vml) {
				for (var e in els) {
					var nodeStr = lib.ns + ':' + e;
					el.vml[r][e] = document.createElement(nodeStr);
				}
				el.vml[r].shape.stroked = false;
				el.vml[r].shape.appendChild(el.vml[r].fill);
				el.parentNode.insertBefore(el.vml[r].shape, el);
			}
			el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
			el.vml.image.fill.type = 'tile'; /* Ze magic!! Makes image show up. */
			el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
			
			lib.attachHandlers(el);
			
			lib.giveLayout(el);
			lib.giveLayout(el.offsetParent);
			
			/* set up element */
			lib.applyVML(el);
		}
		
	};
	try {
		document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
	} catch(r) {}
	DD_belatedPNG.createVmlNameSpace();
	DD_belatedPNG.createVmlStyleSheet();
	
	//DD_belatedPNG.fix('.dl_bundle_thumbnail_delete img,.dl_bundlebg');
}

// 他のダウンロードページ遷移時に警告表示
function outboundConfirm() {
  var dlcnt = $('#dl_status_count').html();
  if(dlcnt == null || dlcnt == '' || dlcnt == '0') return true;
  var msg = '※%current%以外のページに遷移すると、チェックは解除されてしまいます。';
  return confirm(msg.replace('%current%', $('ul.dl_categorymenu .current').text()));
};

function removeArrayEmptyValue(arr) {
  if( arr == null ) {
    return new Array();
  }
  
  var newArr = new Array();
  for(var i = 0; i < arr.length; i++) {
    if( arr[i] != null && jQuery.trim(arr[i]) != "" ) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

function fileCheckInitialize() {
  var ids = jQuery("#normal_form_fileIds").val();
  ids = removeArrayEmptyValue(ids.split(","));
  return ids.join(",");
};

var FileAttach = {
  attach:function(){}
};

var DLItem = {
  highlight:function(){},
  unhighlight:function(){},
  rm:function(){},
  add:function(){},
  update:function(){},
  applyPgUrl:function(){}
};

//まとめてダウンロードパネル表示高さ(標準用、ワーニング有り用)
var DLPanelHeight = [75,100]; //px

(function($){ 
  
  //まとめてダウンロードパネル関連操作定義
  $.extend(DLItem, {
    
    //資料アイテムのハイライト(個別削除ボタン表示)
    highlight:function(){
      $(this).addClass("highlight");
    },
    
    //資料アイテムのハイライト(個別削除ボタン非表示)
    unhighlight:function(){
      $(this).removeClass("highlight");
    },
    
    //資料アイテムの削除
    rm:function(){
      if (arguments.length <= 0 ) return false;
      var $this = arguments[0];
      var item;
      var docId;
      var docSize;
      
      if ($this.attr("type") == "checkbox") {
        //checkbox operation
        docId = $this.val();
        item = jQuery("#dl_item"+docId);
        docSize = $this.attr("sizes");
    
      } else {
        //delete button operation
        item = $this.parents(".item");
        docId = item.attr("docId");
        docSize = item.attr("docSize");
      } 
      
      this.update("-", docId, docSize);
      this.applyPgUrl();
      this.ajaxUpdate("-", docId);
      
      return false;
    },
    
    //資料アイテムの追加
    add:function(){
      if (arguments.length <= 0) return;
      var $this = $(arguments[0]);
      if ($this.attr("type") != "checkbox") return;

      var docId = $this.val();
      var docSize = $this.attr("sizes");
      var imgUrl = $("#dl_table_" + docId + " .dl_itemimg").find("img").attr("src");
      var docTitle = $("#dl_table_" + docId + " .file_name_type .file_name a").html();

      this.update("+", docId, docSize, imgUrl, docTitle);
      this.applyPgUrl();
      this.ajaxUpdate("+", docId, docSize, imgUrl, docTitle);
    },
    
    update:function(op, docId, docSize, imgUrl, docTitle){
      var fileIds = $("#normal_form_fileIds").val();
      var fileSizes = $("#normal_form_fileSizes").val();
      fileIds = removeArrayEmptyValue(fileIds.split(","));
      
      if (op == "+") {        //資料追加
        fileSizes = (fileSizes==''?0:parseInt(fileSizes)) + parseInt(docSize);
        fileIds.unshift(docId);
        
      } else if (op == "-") {
        //資料削除
        fileSizes = parseInt(fileSizes) - parseInt(docSize);
        for (var i = 0; i < fileIds.length; i++) {
          if (fileIds[i] == docId) {
            fileIds.splice(i,1);
          }
        }
      }
      
      fileIds = fileIds.join(",");
      $("#normal_form_fileIds").val(fileIds);
      $("#normal_form_fileSizes").val(fileSizes);
      
      this.redrawDLPanel(op, docId, docSize, imgUrl, docTitle);
    },
    
    applyPgUrl:function(){
      var listType = $("#normal_form_listType").val();
      var sort = $("#normal_form_sort").val();
      
      $.each($(".SearchPageing > ul > li > a"), function(){
        var targetSource = $(this);
        var href = targetSource.attr("href");
        href = href.replace(/\?.*/g, "");
        href = href.replace(/\/{1,}$/, "");
        
        href += "/?listType=" + listType;
        href += "&sort=" + sort;
        href += "&self=1";
        
        targetSource.attr("href", href);
      });
    },    
    redrawDLPanel:function(op, docId, docSize, imgUrl, docTitle){
      
      var tr = $("#dl_table_"+docId);
      
      if (op == "+") {
        tr.addClass("dl_table_check").removeClass("dl_table_nocheck");
        
        $('.panel-container').animate({marginLeft: 0}, 250, "easeInOutExpo");
        
        $(".panel-container .panel:first").prepend(
          '<li class="item" id="dl_item'+docId+'" docId="'+docId+'" docSize="'+docSize+'" style="display:none;">'+
            '<div class="item_mask" id="mask'+docId+'" title="'+docTitle+'">'+
              '<a class="delete" id="del'+docId+'" href="javascript:void();"><img src="/css/images/delete.jpg"></a>'+
            '</div>'+ 
            '<img height="50" alt="'+docTitle+'" src="'+imgUrl+'">'+
          '</li>'
        );

        $(".panel-container .item_mask:first").hover(DLItem.highlight,DLItem.unhighlight);
        $(".panel-container .delete:first").click(function(){
          DLItem.rm($(this));
          return false;
        });

        $(".panel-container .item_mask:first").tipsy({gravity:'s',fade:false});
        $(".panel-container .item:first").fadeIn(1000);
        
        $("#coda-slider").codaSlider();
        
      } else if (op == "-") {
        tr.addClass("dl_table_nocheck").removeClass("dl_table_check");
        tr.find(":input[type='checkbox']").attr("checked", "");
        
        var sz = $('.panel-container .item').size();
        var idx = 0;
        for (var i = 0; i < sz; i++) {
        	var cur = $('.panel-container .item').eq(i);
        	if (cur.attr("docid") == docId) {
        		idx = i;
        		break;
        	}
        }
        var offset = (-310) * Math.floor(idx / 5);
        $('.panel-container').animate({marginLeft: offset}, 250, "easeInOutExpo");
        
        var item = jQuery("#dl_item"+docId);
        item.find(".item_mask").unbind("mouseover").unbind("mouseout");
        
        $(".tipsy").remove();
        
        item.fadeOut(1000, (function(_obj){
          return function() {
            _obj.remove();
/*
            var plen = $(".panel-container .panel").length;
            for (var i = 0; i < plen - 1; i++) {
              var nxt = $(".panel-container .panel:eq(" + (i+1) + ")");
              if (nxt) {
                nxt.find(".item:first").appendTo(".panel-container .panel:eq(" + i + ")");
              }
              if (nxt.find(".item").size() == 0) {
                nxt.remove();
                //$("#coda-slider").codaSlider();
                break;
              }
            }
*/
            var curSz = $('.panel-container .item').size() - 1;
            if (curSz < 0) curSz = 0; 
            var curOffset = $('.panel-container').css("marginLeft");
            if (((-310) * Math.floor(curSz / 5)) > parseInt(curOffset)) {
            	curOffset = (-310) * Math.floor(curSz / 5);
            	$('.panel-container').animate({marginLeft: curOffset}, 250, "easeInOutExpo");
            }
            
            $("#coda-slider").codaSlider();
            
            return false;
          };
        })(item));
      }
      
      var fileIds = $("#normal_form_fileIds").val();
      var fileSizes = $("#normal_form_fileSizes").val();

      fileIds = removeArrayEmptyValue(fileIds.split(","));
      if (fileIds.length == 0) {
        unfixedUI();
        
      } else {
        var hasAlert = 0;
        if (fileSizes > 1024 * 1024 * 20) {
          hasAlert = 1;
        }
        fixedUI(hasAlert);
      }
      
      $('#dl_status_count').html((fileIds.length).toString());
      $('#dl_status_sizes').html(this.editSizes(fileSizes));
    },
    
    // 1MB未満はKB表示、1MB以上はMB表示に編集
    editSizes:function(bytes){
      var kb = bytes/1024;
      var mb = kb   /1024;
      var sizeStr = '<strong>%sizes%</strong> %units%';
      // KBは小数点以下切上げ
      if (mb < 1) {
        kb = (Math.ceil(kb)).toString();
        return sizeStr
          .replace('%sizes%', kb)
          .replace('%units%', 'KB');
      // MBは小数点第二位を切上げ
      } else {
        mb = (Math.ceil(mb * 10) / 10).toString();
        if(mb.indexOf('.')==-1) mb+='.0';
        return sizeStr
          .replace('%sizes%', mb)
          .replace('%units%', 'MB');
      }
    },

    ajaxUpdate:function(op, docId, docSize, imgUrl, docTitle){
      var allDocIds = $("#normal_form_fileIds").val();
      
      if (op == "+") {
        var data = {
          dataKbn:dataKbn,
          allDocIds:allDocIds,
          docId:docId,
          docSize:docSize,
          imgSrc:imgUrl,
          title:docTitle
        };
        $.ajax({
          type: "POST",
          async: false,
          url: "/frontend/download/ajaxAdd.do",
          data: data,
          success: function(out){
            if (out != "") {
              //error!
            }
          }
        });
        
      } else if (op == "-") {
        var data = {
          dataKbn:dataKbn,
          allDocIds:allDocIds,
          docId:docId
        };
        $.ajax({
          type: "POST",
          async: false,
          url: "/frontend/download/ajaxRemove.do",
          data: data,
          success: function(out){
            if (out != "") {
              //error!
            }
          }
        });
      }
    }
  });
  
  $.extend(FileAttach, {
    attach:function(){
      if (arguments.length > 0) {
        var $this = arguments[0];
        if ($this.attr('checked')) {
          var dlcnt = $('#dl_status_count').html();
          if (dlcnt != null && dlcnt != '' && parseInt(dlcnt) >= 20) {
        	$this.attr('checked',"");
        	alert("一度に選択できる資料は、20件までです。");
        	return;
          }
        }
        $this.attr("disabled", "disabled");//連打防止用
        if ($this.attr('checked')) {
          DLItem.add($this);
        } else {
          DLItem.rm($this);
        } 
        //連打防止用
        setTimeout(function(){
          $("#dl_table :input[type='checkbox']").attr("disabled", "");
        },1000);
      }
    }
  });
})(jQuery); 


var fixedUI = function(hasAlert) {
  
  $("#margin").css("display", "block");
  
  var pnlHeight = DLPanelHeight[hasAlert]+"px";
  
  if ($.browser.msie && $.browser.version < 7.0) {

    if ($("#dl_ifie6").css("height") != pnlHeight) {
      if (fixedObjIF) {
        fixedObjIF.resize({
          left:'0',
          bottom:'0',
          width:'100%',
          height:pnlHeight
        });
      }

      fixedObj.fixedOpen(function(){
        var size={
          left:'0',
          bottom:'0',
          width:'100%',
          height:pnlHeight
        };
        fixedObj.getTarget().animate(fixedObj.getFixedSize(size),function(){
            fixedObj.fixedClose(size);
        });
      });
    }
    
  } else {
    var container = $('#dl_all_container'); 
    container.css("height", pnlHeight);
    container.slideDown();
  }

  if (hasAlert == 1) {
    $('#dl_status_alert').show();
  } else {
    $('#dl_status_alert').hide();
  }
};

// $.unfixedUI
var unfixedUI = function() {
  
  if ($.browser.msie && $.browser.version < 7.0) {
    if (fixedObjIF) {
    	fixedObjIF.resize({
    		left:'0',
    		bottom:'0',
    		width:'100%',
    		height:'0px'
    	});
    }
    
    if ($('div.dl_all_panel').css("height") == "0px") {      return;
    }
    fixedObj.fixedOpen(function(){
      var size={
        left:'0',
        bottom:'0',
        width:'100%',
        height:'0px'
      };
      fixedObj.getTarget().animate(fixedObj.getFixedSize(size),function(){
          fixedObj.fixedClose(size);
      });
    });
  } else {
    $('#dl_all_container').slideUp();
  }
  $("#margin").css("display", "none");
};

changeSort = function(val){
  $("#normal_form_sort").val(val);
  normalSelectSubmit();
};

changeShow = function(val){
  var curpg = $("#normal_form_currentPage").attr("lang");
  if (!isNaN(curpg)) {
    $("#normal_form_currentPage").val(curpg);
  }
  $("#normal_form_listType").val(val);
  normalSelectSubmit();
};

var CHK_LOCK = "";

var fixedObj;
var fixedObjIF;//for IE6

jQuery(document).ready(function(){
  $("#footer").css("margin-top","0");

  $('#query_delegate_trigger').bind("click", function(){
    var keywd = $('#keyword').val();
    var url =  "/frontend/search/search.do?searchType=siteSearch"; 
    if (keywd != null && keywd != "") {
      url += "&encodeKeyword=" + keywd;
    }
    location.href = url;
    return false;
  });

  jQuery(function($){
    fixedObj = $('div.dl_all_panel').exFixed({
      api:true,
      dynamicFixed:true,
      bottom:0,
      left:0
    });
  });
  $('div.dl_all_panel').css("width", "100%");

  if ($.browser.msie && $.browser.version < 7.0) {
    if ($("#dl_ifie6").length == 0) {
      $("body").append("<iframe id='dl_ifie6' frameborder='0' scrolling='no' />");
      $("#dl_ifie6").css({
        bottom:"0px",
        left:"0px",
        width:"100%",
        height:"0px",
        display:"block",
        zIndex:"900",
        filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=10)"
      });
    }

    fixedObjIF = $("#dl_ifie6").exFixed({
    	api:true,
    	dynamicFixed:true,
    	bottom:0,
    	left:0
    });
    $("#dl_ifie6").css("width", "100%");
    
    DD_belatedPNG.fix('.dl_bundle_thumbnail_delete img,.dl_bundlebg');
  }
  
  $('.dl_checkbox').click(function(){
    if (CHK_LOCK != $(this).val) {
      CHK_LOCK = $(this).val;
    }
    FileAttach.attach($(this));
  });

  $('.dl_checkbox').parents(".dl_table_checkarea").click(function(){
    var chkbx = $(this).find(".dl_checkbox");
    if (CHK_LOCK == chkbx.val) {
      CHK_LOCK = "";
      return;
    }
    if (chkbx.attr("disabled")) return; //連打防止
    	
    if (chkbx.attr("checked")) {
      chkbx.attr("checked", "");
    } else {
      chkbx.attr("checked", "checked");
    }
    FileAttach.attach(chkbx);
  });

  //全て削除
  $("#dl_delete_all").bind("click", function(){
    var btn = confirm('追加した資料を全て削除します。よろしいですか？');
    if (!btn) return false;
	  
    var data = {
      dataKbn:dataKbn
    };
    $.ajax({
      type: "POST",
      async: false,
      url: "/frontend/download/ajaxRemove.do",
      data: data,
      success: function(out){
        if (out != null) {
    	  //error!
        }
      }
    });
    unfixedUI();
    $("#coda-slider > .panel-container > .panel").slice(1).remove();
    $("#coda-slider > .panel-container > .panel").html("");
    $("#dl_table :input[type='checkbox']").attr("checked", "");
    $(".dl_table_check").removeClass("dl_table_check").addClass("dl_table_nocheck");
    $("#normal_form_fileIds").val("");
    $("#normal_form_fileSizes").val("0");
    $('#dl_status_count').html("0");
    $('#dl_status_sizes').html(DLItem.editSizes(0));
    $("#coda-slider").codaSlider();
    return false;
  });

  $("#coda-slider").codaSlider();

  $("#normal_form_fileIds").val("");
  $("#normal_form_fileSizes").val("");
  $("#dl_table :input[type='checkbox']").attr("checked", "");
  $(".dl_table_check").removeClass("dl_table_check").addClass("dl_table_nocheck");
  
  var data = {
    dataKbn:dataKbn
  };
  $.ajax({
    type: "POST",
    dataType: "json",
    async: false,
    url: "/frontend/download/ajaxList.do",
    data: data,
    success: function(out){
      if (out == null || out == "") {
    	return;
      }
      var allDocIds = out.allDocIds;
      var arr = out.list;
      while (arr != null && arr.length > 0) {
    	var item = arr.pop();
    	DLItem.update("+",item.id,item.size,item.img,item.title);
    	if (!$("#DOC"+item.id).attr("checked")) {
    		$("#DOC"+item.id).attr("checked", "checked");
    	}
      }
    }
  });
  
  //ページング用URLを加工
  DLItem.applyPgUrl()
});

