var linesGroups = [];
var allLines = [];
var allSame = [];
var allMulti = [];

function engravingLinesCheck( ctrl ){
  var $ctrl = $(ctrl);
  var $ctrlIn = $ctrl;
  var onlyRead = false;
  while( true ) {
    if ( !$ctrl.attr('next') ) break;
    if ( onlyRead==false ) {
      onlyRead = ($ctrl.attr('defText')===$ctrl.val() || $ctrl.val()=='');
    }	
    $ctrl = allLines.filter('input[name="'+$ctrl.attr('next')+'"]');
    if ( $ctrl.length==0 ) break;
    if ( onlyRead ) {
      $ctrl.val($ctrl.attr('defText'));
      $ctrl.attr('disabled','disabled');
    }else{
      $ctrl.attr('disabled',null);
    } 
  }
  if ( $ctrlIn.attr('locked') ) {
    var filterCondition = $ctrlIn.attr('locked'); 
    allLines.filter( filterCondition ).each( function() {
      if ( $(this)==$ctrlIn || $(this).attr('disabled') || $(this).attr('multilines_state')==='on' || ($ctrlIn.attr('locked') != $(this).attr('locked'))) return;
      //$(this).val( $ctrlIn.val() );
	  //alert($ctrlIn.attr('locked') + " " + $(this).attr('locked') + " " + this.name);
	  this.value = $ctrlIn.val();
      if ( typeof this.change == 'function' ) this.change();
      allLines.filter('input[name="'+$(this).attr('next')+'"]').attr('disabled',null);
    } );
  }
}
var lastPreviewId = '';
var filteredPreviewLines = [];
var lastPreviewCtrl = false;

function engravingHidePreview(ctrl){
  if ( lastPreviewCtrl ) lastPreviewCtrl.hide();
  lastPreviewId = '';
  filteredPreviewLines = [];
  lastPreviewCtrl = false;
}
  
function engravingShowPreview( ctrl, show ){
  if ( show ) {
    if ( $(ctrl).attr('multilines_state')==='on' ) {
      var multiFlagCtrl = allMulti.filter('input[value="'+ctrl.name+'"]').get(0);
      if ( multiFlagCtrl && typeof multiFlagCtrl.checked != 'undefined' && multiFlagCtrl.checked ) {
        engravingFillMulti(ctrl);
        return;
      }
    }

    var rmatch = /(.*?)\[(\d*)\]\[(\d*)\]$/.exec(ctrl.name);
    if ( lastPreviewId!='preview_'+rmatch[2] ) {
      if ( lastPreviewCtrl ) lastPreviewCtrl.hide();
      lastPreviewId = 'preview_'+rmatch[2];
      lastPreviewCtrl = $('#'+lastPreviewId);
      filteredPreviewLines = allLines.filter('input[name^="lines['+rmatch[2]+']"]');
      engravingFillPreview(rmatch[2]);
      lastPreviewCtrl.show();
    }
  }else{
    engravingHidePreview(ctrl);
  }
}

function cartViewMulti(uprid,lineIdx){
  if ( !window.attachedMultiLinesForm ) {
    $('body').append('<div id="multiLinesDiv" style="display:none;"><div class="engravingPopup"><div class="popup-header">Multiple lines of engraving<a href="javascript:;" onclick="$.closePopupLayer(\'multiLinesPopup\')" title="Close" class="close-link">Close</a><br clear="all" /></div><div class="popup-body" id="multiLinesContainer"><code><pre> </pre></code></div></div></div>')
    window.attachedMultiLinesForm = true;
  }
  $.getJSON('price_engraving.php?get=multi&products_id='+uprid+'&line='+lineIdx, function(data){
    if ( data && data.length>0 ) {
      var TRs = [];
      for( var i=0; i<data.length; i++ ) {
        TRs.push('<tr><td>'+(i+1)+'</td><td>'+data[i]+'</td></tr>');
      }
      $('#multiLinesContainer').html('<table>'+TRs.join('')+'</table>');
      $.openPopupLayer({
        name: "multiLinesPopup",
        width: 320,
        target: "multiLinesDiv"
      });
    }
  });
  return false;
}

function engravingFillMulti(ctrl){
  if ( !window.attachedMultiLinesForm ) {
    $('body').append('<div id="multiLinesDiv" style="display:none;"><div class="engravingPopup"><div class="popup-header">Multiple lines of engraving<a href="javascript:;" onclick="$.closePopupLayer(\'multiLinesPopup\')" title="Close" class="close-link">Close</a><br clear="all" /></div><div class="popup-body" id="multiLinesContainer"><code><pre>$.openPopupLayer({</pre></code></div></div></div>')
    window.attachedMultiLinesForm = true;
  }
  var $srcCtrl = $(ctrl);
  $srcCtrl.val(defaultMultiEngravingText);
  if ( typeof $srcCtrl.change == 'function' ) $srcCtrl.change();
  
  var countLines = $srcCtrl.attr('multiengraving');
  var TRs = [];
  var inputAttributes = ' size="30"';
  if ( $srcCtrl.attr('maxlength') ) {
    inputAttributes += ' maxlength="'+$srcCtrl.attr('maxlength')+'"';
  }
  for( var i=1; i<=countLines; i++ ) {
    TRs.push('<tr><td>'+i+'</td><td><input type="text" name="multilinesEngraving"'+inputAttributes+'></td></tr>');
  }
  $('#multiLinesContainer').html('<table>'+TRs.join('')+'</table>');
  
  engravingHidePreview(ctrl);
  
  $.openPopupLayer({
    name: "multiLinesPopup",
    width: 320,
    target: "multiLinesDiv",
    countLines : countLines,
    srcCtrl : $srcCtrl,
    beforeClose:function(){
      var $container = $('#popupLayer_multiLinesPopup').find('#multiLinesContainer');
      var multiText = [];
      $container.find('input[name="multilinesEngraving"]').each( function(){
        multiText.push($(this).val());
      });
      $('input[name="multi'+this.srcCtrl.get(0).name+'"]').val( multiText.join('\n') );
      estimateSelection($srcCtrl.get(0).form);
    }
	});
  var $container = $('#popupLayer_multiLinesPopup').find('#multiLinesContainer');
  var hiddenLines = $('input[name="multi'+ctrl.name+'"]').val();
  var multiValues = hiddenLines.split(/\n/);
  var idx=0;
  $container.find('input[name="multilinesEngraving"]').each( function(){
    $(this).val( multiValues[idx]?multiValues[idx]:'' );
    idx++;
  });
	$container.find('input:first').focus();
  return;
}

function engravingFillPreview( groupIdx, control ){
  if ( lastPreviewId=='' ) return;
  if ( groupIdx=='' && typeof control.name != 'undefined' ) {
    groupIdx = $(control).attr('linesGroup');
  }
  var typedTextArr = [];
  filteredPreviewLines.each(function(){
    $ctrl = $(this);
    if ($ctrl.attr('defText')===$ctrl.val() || $ctrl.val()=='') return;
    typedTextArr.push( $ctrl.val().replace('<','&lt;').replace('>','&gt;') );
  });
   if ( typedTextArr.length==0 ) {
    lastPreviewCtrl.html('<span><div class="engravingLinesPreviewPopupIn"><div class="engravingLines_tl"><div class="engravingLines_tr"><div class="engravingLines_bl"><div class="engravingLines_br">'+defaultPreviewText+'</div></div></div></div></div></span>');
  }else{  
    lastPreviewCtrl.html('<span><div class="engravingLinesPreviewPopupIn"><div class="engravingLines_tl"><div class="engravingLines_tr"><div class="engravingLines_bl"><div class="engravingLines_br">'+typedTextArr.join('<br />')+'</div></div></div></div></div></span>');
  } 
} 
// {{ photo stuff
function doPhotoUpload(fileCtrl) {
  var req = new JsHttpRequest();
  req.onreadystatechange = function() {
    if (req.readyState == 4) {
      if ( req.responseJS.err!=null && req.responseJS.err!=undefined ) {
        alert( req.responseJS.err );
      }
      var frm = req.fileCtrl.form;
      if ( req.responseJS.photo!=null && req.responseJS.photo!=undefined ) {
        if ( frm.ophoto_engraving1!=null && frm.ophoto_engraving1!='undefined' ) frm.ophoto_engraving1.value= req.responseJS.photo;
        PhotoFileClear('photo_engraving1');
        $('#buttonRemove').show();
        if ( req.responseJS.imagew!=null && req.responseJS.imagew!=undefined ) {
          var sImage = document.getElementById('photo1');
          while (sImage.childNodes.length){ sImage.removeChild(sImage.childNodes[sImage.childNodes.length - 1]); }
          var im = new Image();
          im.src = req.responseJS.src;
          im.width = req.responseJS.imagew;
          im.height = req.responseJS.imageh;
          sImage.appendChild(im);
        }
      }
    }
  }
  req.caching = false;
  req.fileCtrl = fileCtrl;
  req.open(null, 'form.POST photofileupload.php', true);
  var requestData = { photo_engraving1: fileCtrl };
  requestData[ uplSessionK ] = uplSessionV; 
  req.send( requestData );
}
function doPhotoRemove(ctrlId){
  var sImage = document.getElementById('photo1');
  if ( sImage!=null ) while (sImage.childNodes.length){ sImage.removeChild(sImage.childNodes[sImage.childNodes.length - 1]); }
  $('#'+ctrlId).val('');
  $('#buttonRemove').hide();
  PhotoFileClear('photo_engraving1');
}
function PhotoFileClear(contid){
  var cl_f_cont = document.getElementById(contid);
  if ( cl_f_cont!=null && cl_f_cont!='undefined' ) {
    var newF = document.createElement('INPUT');
    newF.name=contid;
    newF.type='file';
    while (cl_f_cont.childNodes.length){ 
      cl_f_cont.removeChild(cl_f_cont.childNodes[cl_f_cont.childNodes.length - 1]); 
    }
    cl_f_cont.appendChild(newF);
  }
}
// }} photo stuff
// {{ PCC stuff
var label_min_width = 100;
var label_max_width = 150;
var select_min_width = 200;
var select_max_width = 350;

function NewWindow(url, myname, w, h, scroll, id) {
   var winl = (screen.width - w) / 2;
   var wint = (screen.height - h) / 2;
   winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=1';
   if(id != null) url = url + id.selectedIndex;
   win = window.open(url, myname, winprops);
   if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}
function pccTemplateUpdate(ctrl){
  var rmatch = /^el\[(\d*)\]\[(\d*)\]$/.exec(ctrl.name);
  var counter = rmatch[1];
  if ( counter.length>0 ) {
    estimateSelection( ctrl.form, counter );
  }else{
    estimateSelection( ctrl.form);
  }
}
// }} PCC stuff
function estimateSelection(form, pccEffect){
  if ( !form ) return;
  if ( !form ) return;
  var $form = $(form);

  var formArray = $form.serializeArray();
  var postArray = [];
  for ( var i=0; i<formArray.length; i++ ) {
    if ( formArray[i].name.substring(0, 6)=='lines[' ) {
      var fInput = allLines.filter('input[name="'+formArray[i].name+'"]');
      if ( fInput.length>0 ) {
        if ( $(fInput.get(0)).attr('defText')===formArray[i].value) continue;
      }
    }
    postArray.push( formArray[i] );
  }
  if ( typeof pccEffect != 'undefined' ) {
    postArray.push( {name:'pccEffect', value: pccEffect} );
    $('#pc_configurator_'+pccEffect).find('select[name^="el['+pccEffect+']["]').attr("disabled","disabled");
    $('#pc_configurator_'+pccEffect).find(".error_box").html('').hide();
  }

  $.ajax({
    type: "POST",
    cache: false,
    dataType: 'json',
    url:'price_engraving.php',
    data: postArray,
    success: function(data){
      $("#selectedAmount").html(data[0]);
      $('#selectedCount').html(data[1]);
      if ( typeof pccEffect != 'undefined' ) {
        var $pcc_container = $('#pc_configurator_'+pccEffect);
        $pcc_container.find('select[name^="el['+pccEffect+']["]').attr("disabled",null);
        var result = data[2];
        if ( typeof result.error != 'undefined' ) {
          // update selects
          if (result['error'] == true) {
            $pcc_container.find(".error_box").html(result['error_message']).show();
          }
          $.each(result['products'], function(pIndex, pData) {
            $pcc_container.find("option[value="+pIndex+"]").text(pData);
          });

          $.each(result['elements'], function(eIndex, eData) {
            $pcc_container.find("select[id="+pccEffect+'_'+eIndex+"]").val(eData);

            if (result['productsIds'][eData] > 0) {
              elhref = $pcc_container.find('div[rel="pcelements_'+eIndex+'"]').find("a.infoimg");
              elhref.attr('href',elhref.attr('href').replace(/#.*/, '') + '#' + result['productsIds'][eData])
            }

          });

          $.each(result['statuses'], function(eIndex, eData) {
            $pcc_container.find("img[rel='stImg_" + eIndex + "']").attr('src',elStatuses_arr[eData]);
          });
        }
      }
    }
  }); 
  var vSelectedCount = 0;
  $('input[name^="qty["]', $form).each( function() {
    vSelectedCount += parseInt(this.value);
  });
  $('#selectedCount').html( vSelectedCount );
}

function engravingMultiCheck(group){
  var qtyValue = parseInt( $('input[name="qty'+group+'"]').get(0).value );
  allMulti.filter('input[value^="lines'+group+'"]').each(function(){
    if (qtyValue>1) {
      $(this).attr('disabled',null);
      //11 $('input[name="multi'+this.name+'"]').attr('disabled',null);
      $('input[name="multi'+this.name+'"]').removeAttr('disabled');
      allLines.filter('input[name="'+this.value+'"]').attr('multiengraving',qtyValue);
    }else{
      this.checked = false;
      $(this).attr('disabled','disabled');
      var $multiLineCtrl = $('input[name="multi'+this.value+'"]');
      $multiLineCtrl.attr('disabled','disabled');
      //11 allSame.filter('input[value="'+this.value+'"]').attr('disabled',null);
      allSame.filter('input[value="'+this.value+'"]').removeAttr('disabled');
      var $sourceCtrl = allLines.filter('input[name="'+this.value+'"]');
      $sourceCtrl.attr( {multiengraving:qtyValue, multilines_state:null});
      if ( $sourceCtrl.val()==defaultMultiEngravingText ) {
        var multiLinesVal = $multiLineCtrl.val().split(/\n/);
        $sourceCtrl.val( (multiLinesVal[0]?multiLinesVal[0]:$targetCtrl.attr('defText')) );
      }
    }
  });
}
function updateTotalQtySelected(){
  totalQtySelected = 0;
  $('input[name^="qty["]').each( function() {
    if (this.value>=1) totalQtySelected ++; else this.value = 0;
  } );
  allSame = $('input[name="same"]');
  if (totalQtySelected > 1) { 
	$('input[name^="qty["]').each( function() {
		if (this.value>0) {
		  allSame.filter('input[value^="lines'+this.name.replace('qty','')+'"]').attr('disabled',null);
		}
	} );
  }
}

$(document).ready(function(){
  $('a[rel="lightbox"]').slimbox();
  $('a[rel="lightbox-plants"]').slimbox();
  
  allLines = $('input[name^="lines["]');
  allMulti = $('input[name="multi"]'); 
  allSame = $('input[name="same"]');
  
  allMulti.bind('click', function(){
    var $targetCtrl = allLines.filter('input[name="'+this.value+'"]');
    if ( !this.checked ) {
      $targetCtrl.attr('multilines_state',null);
      if ( $targetCtrl.val()==defaultMultiEngravingText ) {
        var multiLineCtrl = $('input[name="multi'+this.value+'"]');
        var multiLinesVal = multiLineCtrl.val().split(/\n/);
        multiLineCtrl.attr('disabled','disabled');

        var $sameCheckbox = allSame.filter('input[value="'+this.value+'"]');
        //11 if ( $sameCheckbox.attr('disabled') ) $sameCheckbox.attr('disabled',null); 
        if ( $sameCheckbox.attr('disabled') ) $sameCheckbox.removeAttr('disabled');

        $targetCtrl.val( (multiLinesVal[0]?multiLinesVal[0]:$targetCtrl.attr('defText')) );
        engravingLinesCheck( $targetCtrl.get(0) );
      }
    } else {
      $targetCtrl.attr('multilines_state','on');
      var $sameCheckbox = allSame.filter('input[value="'+this.value+'"]');
      if ( $sameCheckbox.get(0).checked ) {
        $sameCheckbox.get(0).checked = false;
        //11 allLines.filter('input[name="'+this.value+'"]').attr('locked',null);
        allLines.filter('input[name="'+this.value+'"]').removeAttr('locked');
        if (typeof $sameCheckbox.get(0).change == 'function' ) $sameCheckbox.get(0).change();
      }
      $sameCheckbox.attr('disabled','disabled'); 

      if (!$targetCtrl.attr('disabled')) {
        var multiLinesCtrl = $('input[name="multi'+this.value+'"]');
        multiLinesCtrl.attr('disabled',null);
        var oldVal = ($targetCtrl.val()!=$targetCtrl.attr('defText')?$targetCtrl.val():'');
        if ( oldVal.length>0 ) {
          if ( multiLinesCtrl.val().length==0 ) multiLinesCtrl.val(oldVal);
        } 
        $targetCtrl.val(defaultMultiEngravingText);
      }else{
        this.checked = false;
      }
    }
  }); 

  allMulti.each( function(){
    if ( this.checked /*&& typeof this.click == 'function'*/ ) {
      this.checked = false;
      this.click();
    }
  } );

  $('input[name^="qty["]').each( function() {
    $(this).bind( 'focus', function() {
      if (parseInt(this.value)==0) this.value = '';
      engravingMultiCheck(this.name.replace('qty',''));
    } );
    $(this).bind( 'blur', function() {
      if (this.value=='') this.value = '0';
      engravingMultiCheck(this.name.replace('qty',''));
    } );
    $(this).bind( 'keyup', function() {
      estimateSelection(this.form);
      engravingMultiCheck(this.name.replace('qty',''));
    } );
    $(this).bind( 'change', function() {
      estimateSelection(this.form);
      engravingMultiCheck(this.name.replace('qty',''));
	  //updateTotalQtySelected();
    } );
    engravingMultiCheck(this.name.replace('qty',''));
  } );
   
  allLines.each( function(){
    var rmatch = /(.*?)\[(\d*)\]\[(\d*)\]$/.exec(this.name);
    var idx = rmatch[3];
    if (idx=='1') {
      linesGroups.push(this.name)
    }
    var defText = defaultEngravingText.replace('%s',idx);
    var $ctrl = $(this);
    $ctrl.attr('defText', defText); 
    if ( $ctrl.val()=='' ) {
      $ctrl.val( defText );
    }
    $ctrl.attr( { 'linesGroup':rmatch[2], 'next':rmatch[1]+'['+rmatch[2]+']['+(parseInt(idx)+1)+']' });
    $ctrl.bind('focus', function() {
      var $input=$(this);
      if($input.attr('defText')===$input.val()) $input.val('');
      engravingShowPreview(this,true);
    } );
    $ctrl.bind('blur', function() {
      var $input=$(this);
      if(''===$input.val()) $input.val($input.attr('defText'));
      engravingShowPreview(this,false);
      estimateSelection(this.form);
    } );
    $ctrl.bind('keyup', function(){ engravingLinesCheck(this); engravingFillPreview('',this); });
    $ctrl.bind('change', function(){ engravingLinesCheck(this); engravingFillPreview('',this); });
  } );
  $('input[name^="use_logo"]').bind('click', function(){ estimateSelection(this.form);} );
  
  for(var i=0; i<linesGroups.length; i++){
    var $firstLine = $('input[name="'+linesGroups[i]+'"]');
    if ($firstLine.length>0) engravingLinesCheck($firstLine.get(0));
  }
  $('td.engravingSameCell').show();
  $('td.engravingMultiCell').show();
  
  allSame.bind('click', function(){
    // need minimum 2 qty control with qty>0
    var haveSelectedProducts = 0;
    $('input[name^="qty["]', $(this.form)).each( function(){ if ( this.value>0 ) haveSelectedProducts++ } );
    if ( this.checked && haveSelectedProducts<=1 ) {
      this.checked = false;
      return;
    }
    var setSource = $(allLines.filter('input[name="'+this.value+'"]').get(0));
    if ( setSource.attr('disabled') && this.checked ) {
      this.checked = false;
      return;
    }
    if ( setSource.length==1 && !setSource.attr('disabled') ) {
      var filterCondition = 'input[name$="'+this.value.replace(/^lines\[\d*?\]/,'')+'"]';
      var this_checked = this.checked; 
       
      if (this_checked) {
        var setText = setSource.val();
        allLines.filter(filterCondition).each(  function() {
          var $setCtrl = $(this);    

          if ( !$setCtrl.attr('disabled') ) {
            //$setCtrl.attr('locked', filterCondition);
            if ( $setCtrl.attr('multilines_state')==='on' ) {
            }else{
              var qty_ok = ($('input[name^="' + this.name.replace(/^lines(\[\d*\])\[\d*\]/,'qty$1') + '"]').val() > 0);
              if(qty_ok) {
                this.value = setText; 
                //VL ?? $setCtrl.val( setText ).change(); 
                //11 +
                $setCtrl.val( setText ).change(); 
                $setCtrl.attr('locked', filterCondition);
              } 
            }
            allSame.filter( 'input[value$="'+this.name.replace(/^lines/,'')+'"]' ).each( function() {
              if ( $(this).attr('disabled') ) return;
              if(qty_ok) {
                this.checked = this_checked
              }
            });
          }else{
            //11 $setCtrl.attr('locked', null);
            $setCtrl.removeAttr('locked');
          }
        } );
      }else{
        allLines.filter(filterCondition).each(  function() {
          allSame.filter( 'input[value$="'+this.name.replace(/^lines/,'')+'"]' ).each( function() { this.checked = this_checked });
          var $setCtrl = $(this);
          //11 $setCtrl.attr('locked', null);
          $setCtrl.removeAttr('locked');
        } );        
      }
    }
    
  });
  
  $('form[name=listing_rol]').bind( 'submit', function() {
    var checkStatus = true;
    var selectedQty = 0;
    $("input[name^=qty]",$(this)).each( function() { selectedQty+=parseInt(this.value); } );
    checkStatus = selectedQty!=0;
    if ( checkStatus ) {
      allLines.each( function() {
        var $line = $(this);
        if ( $line.val()===$line.attr('defText') ) $line.val(''); 
      } );
    }
    return checkStatus;
  } );
  //$('div.listing_rol_buy_now').floating({targetX:'right', targetY:'bottom'});
  $('#listing_rol_buy_now').addClass('listing_rol_buy_now');
  var floaterContainer = $('#listing_rol_buy_now_contaier');
  if ( floaterContainer.length>0 ) {
    var floaterOffsetLeft = floaterContainer.offset().left + floaterContainer.width() - $('#listing_rol_buy_now').width();
    $('#listing_rol_buy_now').floating({targetX: floaterOffsetLeft , targetY:'bottom'});
  }
  
  estimateSelection( $('form[name=listing_rol]').get(0) );
  $('.haveJs').show();

  // PCC part
  var pcLabels = $("div[rel^='pcelements'] label");

  var max = label_min_width;
  pcLabels.each(function(){
    if ($(this).width() > max) max = $(this).width();
  });
  if (max > label_max_width) max = label_max_width;
  pcLabels.width(max);

  var pcSelects = $("div[rel^='pcelements'] select");
  var max2 = select_min_width;
  pcSelects.each(function(){
    if ($(this).width() > max2) max2 = $(this).width();
  });
  if (max2 > select_max_width) max2 = select_max_width;
  pcSelects.width(max2);
  //pcSelects.bind( 'change', function() {estimateSelection(this.form);} );
  pcSelects.bind( 'change', function() {pccTemplateUpdate(this);} );

  $("div[rel^='pcelements']").find("a.infoimg").bind("click", function(e){
    var url = $(this).attr('href');
    var myname = $(this).attr('title');
    var popw = 650;
    var poph = 650;
    var popscroll = 'yes';
    var winl = (screen.width - popw) / 2;
    var wint = (screen.height - poph) / 2;
    var winprops = 'height='+poph+',width='+popw+',top='+wint+',left='+winl+',scrollbars='+popscroll+',resizable=1';
    var win = window.open(url, myname, winprops);
    if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
    return false;
  });

});

