// ---- SiteCatalyt Directory ----//

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];
    }
  }
  
};

// ---- 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 () {
    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;
  }
});


// events for sitecatalyst
var sc_events = {
  // カート追加：title=sku+':'+products_name
  cart_add: function(title){
    //this._event_click('scAdd','Cart Add Click',title);
  },
  // カート削除
  cart_remove: function(title) {
    //this._event_click('scRemove','Cart Remove Click',title);
  },
  // カート表示
  cart_view: function() {
    //this._event_click('scView','Cart View Click');
  },
  // フォーム開始
  form_start: function(label) {
    if (label == undefined) {
      label = 'Form Start Click';
    }
    this._event_click('event18',label);
  },
  // フォーム完了
  form_complete: function(label) {
    if (label == undefined) {
      label = 'Form Complete Click';
    }
    this._event_click('event19',label);
  },
  // シンプルなイベントクリック
  _event_click: function(events,label,title) {
    var s=s_gi(s_account);
    s.linkTrackVars='events'; 
    s.linkTrackEvents=events; 
    s.events=events; 
    if (title != undefined) {
      s.linkTrackVars+=',products'; 
      s.products = ';'+title;
    }
    s.tl(this,'o',label);
  },

  // チェックアウト:複数製品はcsv=";[sku],;[sku]..."
  checkout: function(products,user_id) {
    this._order_click('scCheckout','Checkout Click',products,user_id);
  },

  // オーダー開始（ログイン:event13）
  order_start: function(products,user_id) {
    //this._order_click('event13','Order Start Click',products,user_id);
  },
  // オーダーStep1（住所入力:event14）
  order_step1: function(products,user_id) {
    //this._order_click('event14','Order Step1 Click',products,user_id);
  },
  // オーダーStep2（支払入力:event15）
  order_step2: function(products,user_id) {
    //this._order_click('event15','Order Step2 Click',products,user_id);
  },
  // 見積表示:event17
  estimate_view: function(products,user_id) {
    //this._order_click('event17','Estimate View Click',products,user_id);
  },
  // キャンセル:event20
  order_cancel: function(products,user_id) {
    //this._order_click('event20','Cancel Click',products,user_id);
  },
  // 購入完了（注文確定:purchase & event16）
  purchase: function(products,user_id,order_id,state,zip) {
    this._order_click('purchase','Purchase Click',products,user_id,order_id,state,zip);
  },
  
  // オーダー関連クリックイベント
  _order_click: function(events,label,products,user_id,order_id,state,zip) {
    var s=s_gi(s_account);
    s.linkTrackVars='products,events,eVar9,eVar24'; 
    s.linkTrackEvents=events; 
    s.events=events; 
    s.products = products;
    if (order_id != undefined) {
      s.linkTrackVars+=',purchaseID'; 
      s.purchaseID=order_id;
    }
    if (state != undefined) {
      s.linkTrackVars+=',state'; 
      s.state=state;
    }
    if (zip != undefined) {
      s.linkTrackVars+=',zip'; 
      s.zip=zip;
    }

    var is_member = 1;
    if (user_id == '' || user_id == '1') {
      is_member = 0;
    }
    s.eVar9=is_member;
    s.eVar24=user_id;
    s.tl(this,'o',label);
  }
};



