// image roll 
function imgRoll(obj,flag) {
  var childNodes = obj.getElementsByTagName('img')[0];
  var pathsrc = childNodes.src;
  var path = pathsrc.slice(0,pathsrc.lastIndexOf("/")+1);
  var imgname = pathsrc.slice(pathsrc.lastIndexOf("/")+1,pathsrc.length);
  if(flag) {
    var imgname = imgname.replace(/_d/i,"_o");
  } else {
    var imgname = imgname.replace(/_o/i,"_d");
  }
  childNodes.setAttribute("src",path + imgname);
}


var parseUri =  function (str) {
  this.url = str;
  this.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
      name:   "queryKey",
      parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
      strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
  }
  
  this.parse = function(){
    var o   = this.options,
      m   = o.parser[o.strictMode ? "strict" : "loose"].exec(this.url),
      uri = {},
      i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
      if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
  }
  
  this.hier = function(strD){
    var u = strD;
    var c = u.split('/');
    c[0] = 'home';
    for(i = 0; i < c.length; i++){
     if(c[i].length == 0){
      c.splice(i,1);
     }
    }
    if (c[c.length - 1].match(/[^0-9]/g)) {
    }else{
      c.splice(c.length - 1,1);
    }
    return c.join(':');
    
  }

  this.type = function(strD){
    var u = strD;
    var c = u.split('/');
    c[0] = 'home';
    for(i = 0; i < c.length; i++){
     if(c[i].length == 0){
      c.splice(i,1);
     }
    }
    return 
    
  }

  
  this.itemID = function(strD){
    var u = strD;
    var c = u.split('/');
    c.reverse();
    for(i = 0; i < c.length; i++){
     if(c[i].length == 0){
      c.splice(i,1);
     }
    }
    if (c[0].match(/[^0-9]/g)) {
      return '';
      }else{
      return c[0];
    }
  }
  
};

// page moving 
function gotop() {
  location.href='http://'+location.host;
}


// url utility
function getq(key) {
  var r = '';
  var re = new RegExp('\\?.*'+key+'=([0-9a-z_\\-%]+)', 'gi');
  var m = re.exec(location.href);
  if (m != undefined) {
    if (m.length > 0) {
      r = m[1];
    }
  }
  return r;
}


// パネルのon/off
function togglePanel(id) {
  var d = document.getElementById(id);
  if (d) {
    if (d.style.display=='') {
      d.style.display='none';
    } else {
      d.style.display='';
    }
  }
}


// hmltエンコード
function htmlencode(str) {
  var encstr = str;
  encstr = encstr.replace("<", "&lt;");
  encstr = encstr.replace(">", "&gt;");
  return encstr;
}


function urlEncode(text){
  var encmsg1 = encodeURI(text);
  var encmsg2;
  var re1 = /\+/gi; var re2 = /\=/gi; var re3 = /\&/gi;
  encmsg2 = encmsg1.replace(re1, "%2B"); //+
  encmsg1 = encmsg2.replace(re2, "%3D"); //=
  encmsg2 = encmsg1.replace(re3, "%26"); //&
  return encmsg2;
}


// HTMLの挿入, docは省略化
function setHtml(id, text, doc){
  var d = document;
  if (arguments.length == 3){
    d = doc;
  }
  var elm = d.getElementById(id);
  if (elm){
    elm.innerHTML = text;
  }
}

// リクエスト for ajax
function requestFile(method, fileName, data, async)
{
  var req = createHttpRequest();
  req.open(method ,fileName ,async);
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  req.onreadystatechange = function()
  { 
    if (req.readyState==4)
    { 
      onReqLoaded(req);
    }
  }
  req.send(data);
}

// XMLHttpRequestオブジェクト生成  for ajax
function createHttpRequest(){
  if(window.ActiveXObject){
    try {
      return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        return new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        return null;
      }
    }
  } else if(window.XMLHttpRequest){
    return new XMLHttpRequest();
  } else {
    return null;
  }
}


function showConf(msg)
{
  if(confirm(msg)){return true;}else{ return false;}
}

function getSelVal(oElem)
{
  var idx = oElem.selectedIndex;
  return oElem.options[idx].value;
}


function getaddr(enddom, startdom, user, islink)
{
  var email = user + '@' + startdom + enddom;
  var link = email;
  if (islink)
    link = '<a href="mailto:'+email+'">'+email+'</a>';
    
  document.write(link);
}


// body.onload 
function init() {}


// サブウインドウを表示
function openSubWin(url, target, width, height, topOffset, noRetObj)
{
  winTop = window.screenTop;
  winLeft = window.screenLeft;
  winWidth = window.document.body.clientWidth;
  winHeigth = window.document.body.clientHeight;
  
  var docLeft = winLeft + winWidth - width;
  var docTop = winTop + topOffset;

  argstr = 'width=' + width + ',height=' + height + ',' +
      'left=' + docLeft + ',top=' + docTop + ',screenX=' + docLeft + ',screenY=' + docTop + ',' +
      'scrollbars=1,resizable=1,status=0,location=0';

  var subwin = window.open(url,target,argstr);
  subwin.focus();
  if (noRetObj){
    return;
  } else {
    return subwin;
  }
}


// おすすめ行追加
function addRowRecom(doc, tableId, rowCountId, inputName, cellDataList, headerExists, optionList)
{
  var oTable = doc.getElementById(tableId);
  var oRowCount = doc.getElementById(rowCountId);
  var rowLen = oRowCount.value;
  if (headerExists)
  {
    rowLen--;
  }
  rowLen++;
  cellDataList[0] = '<input type="hidden" size="4" name="' + createRowControlName(inputName, rowLen, 0) + '" value="' + cellDataList[0] + '" />' + cellDataList[0];
  cellDataList[1] = '<input type="text" size="4" name="' + createRowControlName(inputName, rowLen, 1) + '" value="' + cellDataList[1] + '" />';
  cellDataList[2] = '<input type="text" size="30" name="' + createRowControlName(inputName, rowLen, 2) + '" value="' + cellDataList[2] + '" />';
  cellDataList[3] = '<input type="text" size="30" name="' + createRowControlName(inputName, rowLen, 3) + '" value="' + cellDataList[3] + '" />';
  addRowCount(oTable, oRowCount, cellDataList, headerExists);
}


// 投票行追加
function addRowVote(doc, tableId, rowCountId, inputName, cellDataList, headerExists, optionList)
{
  var oTable = doc.getElementById(tableId);
  var oRowCount = doc.getElementById(rowCountId);
  var rowLen = oRowCount.value;
  if (headerExists)
  {
    rowLen--;
  }
  rowLen++;
  cellDataList[0] = '<input type="hidden" size="4" name="' + createRowControlName(inputName, rowLen, 0) + '" value="' + cellDataList[0] + '" />' + cellDataList[0];
  cellDataList[1] = '<input type="text" size="30" name="' + createRowControlName(inputName, rowLen, 1) + '" value="' + cellDataList[1] + '" />';
  addRowCount(oTable, oRowCount, cellDataList, headerExists);
}


// カテゴリ行追加
function addRowCategory(doc, tableId, rowCountId, inputName, cellDataList, headerExists, optionList)
{
  var oTable = doc.getElementById(tableId);
  var oRowCount = doc.getElementById(rowCountId);
  var rowLen = oRowCount.value;
  if (headerExists)
  {
    rowLen--;
  }
  rowLen++;
  cellDataList[0] = '<input type="text" size="4" name="' + createRowControlName(inputName, rowLen, 0) + '" value="' + cellDataList[0] + '" />';
  cellDataList[1] = '<input type="text" size="30" name="' + createRowControlName(inputName, rowLen, 1) + '" value="' + cellDataList[1] + '" />';
  addRowCount(oTable, oRowCount, cellDataList, headerExists);
}


// 著者行追加
function addRowAuthor(doc, tableId, rowCountId, inputName, cellDataList, headerExists, optionList)
{
  var oTable = doc.getElementById(tableId);
  var oRowCount = doc.getElementById(rowCountId);
  var rowLen = oRowCount.value;
  if (headerExists)
  {
    rowLen--;
  }
  rowLen++;
  var selectControlName = createRowControlName(inputName, rowLen, 2);
  var oMediaSelect = createSelectControl(selectControlName, optionList, "");
  oMediaSelect.name = 
  cellDataList[0] = '<input type="text" size="4" name="' + createRowControlName(inputName, rowLen, 0) + '" value="' + cellDataList[0] + '" />';
  cellDataList[1] = '<input type="text" size="30" name="' + createRowControlName(inputName, rowLen, 1) + '" value="' + cellDataList[1] + '" />';
  cellDataList[2] = oMediaSelect.outerHTML;
  addRowCount(oTable, oRowCount, cellDataList, headerExists);
}


// 行コントロールの名前を作成
function createRowControlName(inputName, rowLen, cellIndex)
{
  return inputName + ':_ctl' + rowLen + ':_ctl' + cellIndex + ':row';
}

// 行の追加
function addRowCount(oTable, oRowCount, cellDataList, headerExists)
{
  var oRow = oTable.insertRow();
  var oCell;
  for(i = 0 ; i < cellDataList.length; i++)
  {
    oCell = oRow.insertCell();
    oCell.innerHTML = cellDataList[i];
  }
  var rowLen = oRowCount.value;
  rowLen++
  oRowCount.value = rowLen;
}


//クリックした行を削除する
function deleteRow(element) {
  var e, r, c;
  if (element == null) {
  e = window.event.srcElement;
  } else {
  e = element;
  }
  c = e.parentElement;
  r = c.parentElement;
  p = r.parentElement;
  p.removeChild(r);
  window.event.cancelBubble = true;
}

// Option要素配列からSelectメニューの作成
function createSelectControl(controlName, optionList, scriptText)
{
  var oSelect = document.createElement('<select name="' + controlName + '"></select>');
  for(i = 0 ; i < optionList.length; i++)
  {
    var optionItem = optionList[i].split("=");
    var oOption = document.createElement("OPTION");
    oOption.value = optionItem[0];
    oOption.text  = optionItem[1];
    oSelect.add(oOption);
  }
  if (scriptText != "")
  {
    var oAttrColl = oSelect.attributes;
    var onChangeScript = oAttrColl.getNamedItem("onchange");
    onChangeScript.value = scriptText;
  }
  return oSelect;
}


// for debug
function dumpobj(obj) {
  for(var prop in obj) {
    try {
      window.document.writeln(prop+' = '+obj[prop]+'<br>');
    } catch(e) {
    }
  }
}


// SiteCatalyst
// arena: event5, evar14 
// hottopics: event5, evar14
// sumitem(ad): event4 evar15=広告クリック
function arena_click(o){
  var s=s_gi(s_account);
  s.linkTrackVars='products,eVar14,events'; 
  s.linkTrackEvents='event5'; 
  s.events='event5'; 
  s.eVar14= o; 
  s.products = o;
  s.tl(this,'o','Arena Click');
}
function hottopics_click(o){
  var s=s_gi(s_account);
  s.linkTrackVars='products,eVar14,events'; 
  s.linkTrackEvents='event5'; 
  s.events='event5'; 
  s.eVar14= o; 
  s.products = o;
  s.tl(this,'o','Hottopics Click');
}


function sumitem_click(o,t){
  var a = new parseUri(o.href);
  var adid = a.itemID(o.href);

  var s=s_gi(s_account);
  s.linkTrackVars='products,eVar15,events'; 
  s.linkTrackEvents='event4'; 
  s.events='event4'; 
  s.eVar15= adid; 
  s.products = adid;
  s.tl(this,'o','Ad Click');
}


function gologin() {
  location.href = "https://sems.shoeisha.com/users/login/codezine?cid=codezine_regist&ref="+encodeURIComponent(location.href);
}

function goregist() {
  location.href = "/user/regist/?cid=codezine_regist&ref="+encodeURIComponent(location.href);
}


function sems_encode(xurl){
  return encodeURIComponent(xurl.replace(/\?/g,"_question_").replace(/&/g,"_ampersand_").replace(/=/g,"_equal_"));
}


// クロスブラウザ用イベント監視
function observe(target, type, listener) {
    if (target.addEventListener) target.addEventListener(type, listener, false);
    else if (target.attachEvent) target.attachEvent('on' + type, function() { listener.call(target, window.event); });
    else target['on' + type] = function(e) { listener.call(target, e || window.event); };
}


// key属性にイベント追加
function set_link_event(key) {
    var links = document.getElementsByTagName('a');
    for(var i=0;i<links.length;i++) {
           if (links[i].rel == key) {
            observe(links[i], 'click', function(e) {
                    // click要素のhrefと座標
                    sc_click_count(location.href, key + ':' + this, e.clientX+','+e.clientY);
                    //pageTracker._trackEvent('LinkClick:'+key, this, location.href);
            });
           }
    }
}
// クリックカウント
function sc_click_count(v1, v2, v3) {
    var s=s_gi(s_account);
    s.linkTrackVars='products,eVar17,eVar18,events';
    s.linkTrackEvents='event2';
    s.events='event2';
    s.products = ';' + v1;
    s.eVar17= v2;
    s.eVar18= v3;
    s.tl(this,'o','Link Click');
}


function ov_click_count(v1, v2, v3) {
  var s=s_gi(s_account);
  s.linkTrackVars='products,eVar19,eVar20,events';
  s.linkTrackEvents='event4';
  s.events='event4';
  s.products = 'ov;' + v1;
  s.eVar19= v2;
  s.eVar20= v3;
  s.tl(this,'o','Overture Click');
}


// ユーザ取得
function sc_user(){
  var jx=jQuery.ajax({
    url: "/api/user",
    dataType: "json",
    async: false
   }).responseText;
  var result = eval('(' + jx + ')');
  return result.shopper_id;
}
// リファラードメイン取得
function sc_referrer(){
  if(document.referrer.replace(/http[s]?:\/\/([^\/]+?)\/.*/i,"$1") == location.hostname){
    return "";
  }
  return document.referrer.replace(/http[s]?:\/\/([^\/]+?)\/.*/i,"$1");
}



$(document).ready(show_left);

function show_left(){
  if ($("#lang_parts")) $("#lang_parts").load("/parts/lang_parts");
  if ($("#ez_patrs")) $("#ez_patrs").load("/parts/ez_patrs");
  if ($("#rz_patrs")) $("#rz_patrs").load("/parts/rz_patrs");

}


// ---- SiteCatalyt Click Events ----//

// <a href="#" 
//    ref="sc" 
//    scCategory="AreaTest" 
//    scVars="14" 
//    scVals="Data" 
//    scEvents="5"  
//    scProducts="%TITLE%" 
//    scLabel="test">Test</a>
// 
//    
//    If you'd like to omit value of attributes 
//    in scProducts,scLabel,scCategory and scVals , 
//    you can set the following value to the attributes.
//    
//    %TITLE% = this anchor text
//    %LOC% = location.href(page url)
//    %HREF% = this anchor href
//    

$(function(){
  if ($("a") == null) return;
  $("a").click(function () {
    try {
      if (s_account == undefined) return;
    } catch(e) { return; }
    
    var ref = $(this).attr("ref");
    if (typeof(ref) == 'undefined' || ref != 'sc') return;
    
    // event
    var events = $(this).attr("scEvents");
    if(typeof(events) == 'undefined'){
        events = '';
    } else {
      events = events.split(',');
    }

    // category
    var category = $(this).attr("scCategory");
    if(typeof(category) == 'undefined'){
        category = '';
    } 
    category = rep_val(category, $(this));
    
    // products
    var products = $(this).attr("scProducts");
    if(typeof(products) == 'undefined'){
        products = $(this).text();
    }
    products = rep_val(products, $(this));

    // eVar
    var eVars = $(this).attr("scVars");
    if(typeof(eVars) == 'undefined'){
        eVars = '';
    } else {
      eVars = eVars.split(',');
    }
    
    // eVal
    var eVals = $(this).attr("scVals");
    if(typeof(eVals) == 'undefined'){
        eVals = '';
    } else {
      eVals = eVals.split(',');
    }
    
    // LABEL
    var linkname = $(this).attr("scLabel");
    if(typeof(linkname) == 'undefined'){
        linkname = $(this).text();
    }
    linkname = rep_val(linkname, $(this));
    
    var s=s_gi(s_account);

    // Set linkTrackVars
    var linkTrackVars = '';
    for ( var i=0; i < eVars.length  ; i++  ){
      linkTrackVars +=  "eVar" + eVars[i];
      if (i != eVars.length -1 ){
         linkTrackVars += ",";
      }
    }
    if (products){
       if (linkTrackVars){
          linkTrackVars += ",products";
       } else {
          linkTrackVars += "products";
       }
    }
    if (events.length > 0){
       if (linkTrackVars){
          linkTrackVars += ",events";
       } else {
          linkTrackVars += "events";
       }
    }
    s.linkTrackVars = linkTrackVars  ;
    
    // Set linkTrackEvents
    var linkTrackEvents = '';
    for ( var i=0; i < events.length  ; i++  ){
      linkTrackEvents +=  "event" + events[i];
      if (i != eVars.length -1 ){
         linkTrackVars += ",";
      }
    }
    s.linkTrackEvents = linkTrackEvents;
    // Set events
    s.events = linkTrackEvents;
    // Set products
    s.products = category + ";" + products;
    
    // Set eVar99
    if ( eVars && eVals ){
       for ( var i=0; i < eVars.length  ; i++  ){
            eVals[i] = rep_val(eVals[i], $(this));
            eval( "s.eVar" + eVars[i] + "='" + eVals[i] + "'");
       }
       
    }
    
    s.tl(this,'o',linkname);
  });
  
  function rep_val(val, elem) {
    if (val) {
      val = val.replace('%TITLE%', elem.text(), 'g');
      val = val.replace('%HREF%', elem.attr('href'), 'g');
      val = val.replace('%LOC%', location.href, 'g');
    }
    return val;
  }
});

