var isbnValid = false;
var lineCnt = 1;

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
} 

function isNumeric(strString) {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;
   if (strString.length == 0) return false;
   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

function isbn13Validates(isbnToCheck) {
    var isbnValid = false;
    if ( $('#genISBN').val() != '' && $('#isbn').val() == $('#genISBN').val() ) { return true; }
    
    var checkDigit = isbnToCheck.substr(12,1);
    var calcDigit = 10 - parseInt(( 
            ( 1 * parseInt(isbnToCheck.substr(0,1)) ) + ( 3 * parseInt(isbnToCheck.substr(1,1)) ) + 
            ( 1 * parseInt(isbnToCheck.substr(2,1)) ) + ( 3 * parseInt(isbnToCheck.substr(3,1)) ) + 
            ( 1 * parseInt(isbnToCheck.substr(4,1)) ) + ( 3 * parseInt(isbnToCheck.substr(5,1)) ) + 
            ( 1 * parseInt(isbnToCheck.substr(6,1)) ) + ( 3 * parseInt(isbnToCheck.substr(7,1)) ) + 
            ( 1 * parseInt(isbnToCheck.substr(8,1)) ) + ( 3 * parseInt(isbnToCheck.substr(9,1)) ) + 
            ( 1 * parseInt(isbnToCheck.substr(10,1)) ) + ( 3 * parseInt(isbnToCheck.substr(11,1)) )) % 10 );
    if ( calcDigit == 10 ) { calcDigit = 0; }
    if ( checkDigit == calcDigit ) { isbnValid = true; }
    return isbnValid;
}

function checkISBN() {
    isbnValid = false;
    if ( $('#genISBN').val() != '' && $('#isbn').val() == $('#genISBN').val() ) { return true; }
    var isbn = new String($('#isbn').val());
    if ( isbn.length > 0  && !isNumeric(isbn) ) {
        alert("Only Numerical values are allowed in the ISBN field");
        $('#isbn').val('');
        setTimeout("$('#isbn').focus()",50);
        return false;
    }
    if ( isbn.length == 13 ) {
        if ( !isbn13Validates(isbn) ) {
            alert("You must enter a 13 digit ISBN number that validates to the 2005 edition of the International ISBN Agency's official manual");
            return false;
        }
    }
}

function getTotalWeight() {
    var totalWeight = 0;

    totalWeight = parseFloat( packagingWeight );

    $('tbody tr').each(function(){
        
        bookId = parseInt($(this).find('.book').val());
        qty = parseInt($(this).find('.quantity').val());
        if ( !isNaN(bookId) && !isNaN(qty) ) {
            totalWeight = totalWeight + parseFloat( qty * parseFloat(bookWeights[bookId]));
        }
            
    })
    
    return totalWeight;
}
function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}
function limitDelivery() {
    var countryID = $('#country').val();

    var totalWeight = getTotalWeight();

    var params = countryID.toString()+'|'+totalWeight.toString();

    $.post('di.php',
			{ 'callback': '?', 'm':'checkDeliveryMethods', 'v':params },
			function (data,status) {
        if ( status == "success" ) {
          var first = true;

          $('#servID option').each(function() {
              $(this).removeAttr("selected");

              $(this).attr("disabled","true");

              // NB Special rule for Fedex
              if ( $(this).val() in oc(data.disps) || $(this).val() == 'FEDEX' && data.fedex ) {
                $(this).removeAttr("disabled");
                if ( first ) {
                  $(this).attr("selected","true");
                  first = false;
                  calcDelivery();
                }
              }
            });
          }
      },'jsonp');
      
}


function calcDelivery() {
    var delivery = 0;
    var servID = $('#servID').val();
    var totalWeight = getTotalWeight();

    var countryID = $('#country').val();

    if ( isNaN(totalWeight) || totalWeight == 0 ) {
        return false;
    }

    // need to work out the correct service id for the country
    if ( servID == "FEDEX" ) {
      if ( !isNaN( dispZones[countryID]['Fedex'] ) ) {
        servID = fedexTrans[ dispZones[countryID]['Fedex'] ] ['ServID'];
      }else{
        return false;
      }
    }

    for ( x in dispPrices ) {
        if ( dispPrices[x]['ServID'] == servID  && dispPrices[x]['max'] >= totalWeight && dispPrices[x]['min'] <= totalWeight ) {
            delivery = dispPrices[x]['price'] + delMod;
            break;
        }
    }
    
    $('tfoot .delivery span').html((delivery).toFixed('2'));
    $('#delivery').val((delivery).toFixed('2'));
    
    return (delivery);
}

function calcTotal() {
    $('.grandTotal span').css('color', '#000');
    $('#placeOrder').attr('disabled','');
    $('#placeOrder').css('background-color','');
    var total = 0;
    //var delivery = 0;
    $('tbody tr').each(function(){
        linePrice = parseFloat($(this).find('.linePrice span').html());
        if ( !isNaN(linePrice) ) {
            total = total + linePrice;
        }
    })
    $('tfoot .total span').html((total).toFixed('2'));
    $('#lineTotals').val((total).toFixed('2'));
    
    delivery = calcDelivery();
    
    valToPut = (parseFloat(total) + parseFloat(delivery)).toFixed('2');
    if ( !isNaN(valToPut) ) {
        $('tfoot .grandTotal span').html(valToPut);
        $('#grandTotal').val(valToPut);
        if ( valToPut > cusbal && precus ) {
            $('.grandTotal span').css('color', '#f00');
            $('#placeOrder').attr('disabled','disabled');
            $('#placeOrder').css('background-color','#ababab');
            alert('The order value exceeds your available balance, please top up your account and re-order');
        }
    }
}

function calcRow(el) {
    if ( $(el).val() != "" && $(el).parent().parent().find('.unitPrice span').html() != "" ){
        lineQty = parseInt($(el).parent().parent().find('.quantity').val());
        linePrice = parseFloat(parseInt($(el).val()) * parseFloat($(el).parent().parent().find('.unitPrice span').html()));
        disc = false;
        dBCnt = 0;
        discId = '';
        while ( dBracketsQty[dBCnt] ) {
            if ( dBracketsQty[dBCnt] <= lineQty ) {
                disc = true;
                discId = dBCnt;
            }
            dBCnt++;
        }
        if ( disc ) {
            linePrice = linePrice * ((100 - dBracketsPerc[discId])/100);
        }
        
        $(el).parent().parent().find('.linePrice span').html( 
            linePrice.toFixed('2')) ;
        calcTotal();
    }
}

function removeLine(line) {
    if ( $(line).find('.lineNo').val() == 1 ) { 
        alert("You cannot remove this order line.");
    }else{
        deadLineNo = $(line).find('.lineNo').val();
        $(line).remove();
        $('.lineNo').each(function() {
            if ( $(this).val() > deadLineNo ) {
                thisLineNo = $(this).val() - 1;
                $(this).val(thisLineNo);
                $(this).attr('name','lineNo-'+thisLineNo);
                $(this).parent().parent().find('.book').attr('name','book-'+thisLineNo);
                $(this).parent().parent().find('.quantity').attr('name','quantity-'+thisLineNo);
            }
        })
        lineCnt--;
    }
    calcTotal();
}

function clearAdd(){
    $('#name').val('');
    $('#addr1').val('');
    $('#addr2').val('');
    $('#addr3').val('');
    $('#addr4').val('');
    $('#town').val('');
    $('#county').val('');
    $('#countryCode').val('');
    $('#areaCode').val('');
    $('#phone').val('');
    
}

$(document).ready( function() {
	if ( $('.inactivator').length ) {
		$('.inactivator').each(function() {
			$(this).click(function(e) {
                if ( confirm('Are you sure you wish to activate this book?') ) {
                	var el = $(this);
                	var id = $(this).attr('rel');
					$.post(
						'di.php',
						{ 'callback': '?', 'm':'activateBook', 'v':id },
						function (data,status) {
							if ( status == "success" && data.active == 1 ) {
								alert("Activated");
                                $(el).replaceWith('<a href="order.php?id='+id+'" title="Order Book" class="boxybtn placeorder">Order Book</a>');
							}
						},
						'jsonp'				
					);
                }
                e.preventDefault();
			});
		});
	}
	
    if ( $('#commAdd').length ) {
        $('#commAdd').change(function(){
            if ( $(this).val() != "" ) {
                if ( commAdds[$(this).val()] != "" ) {
                    if ( commAdds[$(this).val()]['name'] ) { 
                      $('#name').val( commAdds[$(this).val()]['name'] );
                    }
                    if ( commAdds[$(this).val()]['addr1'] ) {
                      $('#addr1').val( commAdds[$(this).val()]['addr1'] );
                    }
                    if ( commAdds[$(this).val()]['addr2'] ) {
                      $('#addr2').val( commAdds[$(this).val()]['addr2'] );
                    }
                    if ( commAdds[$(this).val()]['addr3'] ) {
                      $('#addr3').val( commAdds[$(this).val()]['addr3'] );
                    }
                    if ( commAdds[$(this).val()]['addr4'] ) {
                      $('#addr4').val( commAdds[$(this).val()]['addr4'] );
                    }
                    if ( commAdds[$(this).val()]['town'] ) {
                      $('#town').val( commAdds[$(this).val()]['town'] );
                    }
                    if ( commAdds[$(this).val()]['county'] ) {
                      $('#county').val( commAdds[$(this).val()]['county'] );
                    }
                    if ( commAdds[$(this).val()]['countryCode'] ) {
                      $('#country').val( commAdds[$(this).val()]['countryCode'] );
                    }
                    if ( commAdds[$(this).val()]['areaCode'] ) {
                      $('#areaCode').val( commAdds[$(this).val()]['areaCode'] );
                    }
                    if ( commAdds[$(this).val()]['phone'] ) {
                      $('#phone').val( commAdds[$(this).val()]['phone'] );
                    }
                    limitDelivery(); calcTotal();
                } else {
                    clearAdd();
                }
            } else {
                clearAdd();
            }
        })
    }
    
    if ( $('#addBook').length ) {
        $('#addBook').click(function() {
            var message = '';
            if ( $('#title').val() == "" ) {
                message += '    Book Title has not been entered.\n';
            }
            var isbn = new String($('#isbn').val());

            if ( $('#isbn').val() == "" ) {
                message += '    ISBN has not been entered.\n';
            } else if ( !isbn13Validates(isbn) ) {
                message += '    ISBN must Validate.\n';
            }
            if ( $('#monoPages').val() == "" || ( parseInt($('#monoPages').val()) < 1 && parseInt($('#colPages').val()) < 1 ) ) {
                message += '    Number of Pages must be entered.\n';
            }
            if ( message !== '' ) {
                alert("Please check you have filled in all the necessary details:\n"+message);
                return false;
            }
            $('#addBook').val('Please Wait...')
            $('#addBook').css('background-image','url(../bookvault/images/wait.gif)');
            $('.bookvault').prepend('<p class="info">Thank you. Please be aware if you are uploading files, this may take a few minutes.</p>');
        })
    }
    if ( $('#isbn').length ) {
        $('#isbn').change(function() { checkISBN();})
//        $('#isbn').blur(function() { checkISBN();})
    }
    if ( $('.combo').length ) {
        $('.combo').select_autocomplete();
    }

    if ( $('.newLine').length ) {
        $('.newLine').click(function() {
            /* Increment the line count */
            lineCnt++;
            /* Clone the main orderline */
            clone = $('.orderLine').clone();
            /* remove the class so multiple clones aren't created next time around */
            $(clone).attr('class','');
            /* clear any field values in the clone */
            $(clone).find('.lineNo').val(lineCnt);
            $(clone).find('.lineNo').attr('name','lineNo-'+lineCnt);
            $(clone).find('.book').val('');
            $(clone).find('.book').attr('name','book-'+lineCnt);
            $(clone).find('.unitPrice span').html('0.00');
            $(clone).find('.linePrice span').html('0.00');
            $(clone).find('.quantity').val('');
            $(clone).find('.quantity').attr('name','quantity-'+lineCnt);

            $(clone).find('.removeLine').bind('click', function() { removeLine($(this).parent().parent()); })

            $(clone).find('.quantity').bind('change', function() { if ( !isNumeric($(this).val()) ) { alert('Quantity must be numeric'); $(this).val(''); return false; }; calcRow(this); })

            $(clone).find('.ac_input').remove();
            $(clone).find('.book').select_autocomplete();
            $(clone).find('.ac_input').bind('blur', function() {
                if ( $(this).parent().find('.combo').val() != "" ) {
                    $(this).parent().parent().find('.unitPrice span').html( (bookPrices[$(this).parent().find('.combo').val()] ).toFixed('2'));
                    calcRow($(this).parent().parent().find('.quantity'));
                }
            });
            
            /* append the clone */
            $('.orderLine').parent().append(clone);

            
        })
    }
    
    if ( $('.removeLine').length ) {
        $('.removeLine').click( function() { removeLine($(this).parent().parent()); })
    }
    if ( $('.quantity').length ) {
        $('.quantity').bind('change', function() { if ( !isNumeric($(this).val()) ) { alert('Quantity must be numeric'); $(this).val(''); return false; }; limitDelivery(); calcRow(this); })
    }
    if ( $('.ac_input').length ) {
        $('.ac_input').bind('blur', function() {
            if ( $(this).parent().find('.combo').val() != "" ) {
                $(this).parent().parent().find('.unitPrice span').html( (bookPrices[$(this).parent().find('.combo').val()] ).toFixed('2'));
                calcRow($(this).parent().parent().find('.quantity'));
            }
        })
    }

    /* Recalc Delivery on change of delivery service or country */
    if ( $('#servID').length ) {
        $('#servID').bind('change', function() { calcTotal(); })
    }
    if ( $('#country').length ) {
        $('#country').bind('change', function() { limitDelivery(); calcTotal() })
        limitDelivery();
    }
    
    if ( $('#placeOrder').length ) {
        
        $('#placeOrder').bind('click', function() {
        	$('#placeOrder').attr('disabled','disabled');
            var message = '';
            if ( $('#docRef').val() == "" ) {
                message += '    Your Reference has not been entered.\n';
            }
            if ( $('#name').val() == "" ) {
                message += '    Delivery Name has not been entered.\n';
            }
            if ( $('#addr1').val() == "" ) {
                message += '    At least the First Address Line must be entered.\n';
            }
            if ( $('#town').val() == "" ) {
                message += '    Delivery Town has not been entered.\n';
            }
            if ( $('#country').val() == "" ) {
                message += '    Delivery Country has not been entered.\n';
            }
            if ( $('#areaCode').val() == "" ) {
                message += '    Post Code has not been entered.\n';
            }
            if ( $('#orderLines tbody tr:first .ac_input').val() == "" ) {
                message += '    At least one Book Must be selected.\n';
            }
            if ( $('#orderLines tbody tr:first .quantity').val() == "" ) {
                message += '    A Quantity must be entered for each book.\n';
            }            
            if ( message !== '' ) {
                alert("Please check you have filled in all the necessary details:\n"+message);
                $('#placeOrder').attr('disabled','');
                return false;
            }
            replaceStr = '<p>You are ordering:</p>';
            $('#orderLines tbody tr').each(function (){
                replaceStr += '<p><strong>'+$(this).find('.quantity').val()+' copies</strong> of \'<strong>'+$(this).find('.ac_input').val()+'</strong>\'</p>';
            });
            $('#replaceMe').before(replaceStr).remove();
            $('#dialog0').jqm(); 
            $('#dialog0').jqmShow();
            $('#placeOrder').attr('disabled','');

            return false;
        });
        
    }
    if ( $('#confirmOrder').length ) {
        $('#confirmOrder').bind('click', function() {
            $('#placeOrder').val('Please Wait...');
            $('#placeOrder').css('background-image','url(../bookvault/images/wait.gif)');
            $('#orderform').submit();
        })
    }

    
    if($.browser.msie && parseInt($.browser.version) <= 6){
        $('#ie6').toggle();
    }
    
    if ( $('.approve').length ) {
        $('.approve').each(function() {
            $(this).click(function(e) {
                if ( confirm('Are you sure you wish to approve the proof for this book?') ) {
                    var el = $(this);
                    $.post(
                        $(this).attr('href')+'&callback=?',{},
                        function(data, status) {
                            if ( status == "success" ) {
                                if ( data.save ) {
                                    $(el).removeClass('approve');
                                    $(el).addClass('placeorder');
                                    $(el).empty();
                                    $(el).append('Order Book');
                                    var end = $(el).attr('href').replace('di.php?m=approveBook&v','order.php?id');
                                    $(el).attr('href',end);
                                    $(el).unbind();
                                    $(el).parents('tr').addClass('approveSuccess');
                                    $(el).parents('tr').children('.bookTitle').addClass('updateSuccess').append('<span> - Proof Approved</span>');
                                    setTimeout("$('.approveSuccess').removeClass('approveSuccess');",5000);
                                    setTimeout("$('.updateSuccess span').remove();",5000);
                                    setTimeout("$('.updateSuccess').removeClass('updateSuccess');",5000);
                                }
                            } 
                        },'jsonp'
                    );
                }
                e.preventDefault(); 
            });
        });
    }

    if ( $('.reproof').length ) {
    	setupPopup('class','proofPop');
        $('.reproof').each(function() {
            $(this).click(function(e) {
                var el = $(this);
                var bId = $(this).attr('rel');
                $.post(
                    $(this).attr('href')+'&callback=?',{},
                    function(data, status) {
                        if ( status == "success" ) {
                        	if ( data.err.length ) {
                        		alert(data.err);
                        	}else{ 
	                        	var str = '';
	                    		str += '<div><p><label for="proofID">Proof Type</label><select name="proofID" id="proofID">';
	                        	$(data.p).each(function (i, dat) {
	                        		str += '<option value="' + dat.id + '">' + dat.name + ' (&pound;' + dat.cost + ')</option>';
	                        	});
	                    		str += '</select></p>';
	                    		str += '<p>Note<br/><textarea id="proofNote"></textarea><p><small>NB Ordering a new proof will overwrite all previous Notes.</small></p>';
	                    		str += '<p class="center"><input type="button" class="boxybtn" name="acceptProof" id="acceptProof" value="Order New Proof Type"/></p></div>'
	                        	loadPopup(str, e.pageY, e.pageX);
	                    		$('#acceptProof').click(function(e) {
	                                $.post(
	                                    'di.php?m=getNewProof&v='+bId+'|'+$('#proofID').val()+'|'+$('#proofNote').val()+'&callback=?',{},
	                                    function(data, status) {
	                                    	if ( status == "success" ) {
	                                    		alert('A New Proof was ordered successfully.');
	                                    	}else {
	                                    		alert('There was a problem ordering a new proof.');
	                                    	}
	                                    	var par = $(el).parent();
	                                    	$(par).empty();
	                                    	$(par).html('<small>Title Inactive</small>');
	                                    	disablePopup();
	                                    });
	                    		});
                        	} 
                        } 
                    },'jsonp'
                );
                e.preventDefault(); 
            });
        });
    }
    
    if ( $('#autoISBN').length ) {
        $('#genISBN').val('');
        $('#autoISBN').click(function(e) {
            e.preventDefault();
            // Generate a fake but unique isbn: (cID = Customer ID)
            // format: {cID YY ww D HH ii ss} (no spaces) 
            var weekno = new String(new Date().getWeek());
            while ( weekno.length < 2 ) {
                weekno = '0'+weekno;
            }
            var hour = new String(new Date().getHours());
            while ( hour.length < 2 ) {
                hour = '0'+hour;
            }
            var mins = new String(new Date().getMinutes());
            while ( mins.length < 2 ) {
                mins = '0'+mins;
            }
            var seconds = new String(new Date().getSeconds());
            while ( seconds.length < 2 ) {
                seconds = '0'+seconds;
            }
            var isbnVal = $('#CustID').val();
            while ( isbnVal.length < 3 ) {
                isbnVal = '0'+isbnVal;
            }
            isbnVal = isbnVal + new Date().getFullYear().toString().substr(3); //'y'           '0-9'
            isbnVal = isbnVal + weekno;                                        //'weekno'       '00-52'
            isbnVal = isbnVal + new Date().getDay();                           //'day of week'  '1-7' 
            isbnVal = isbnVal + hour;                                          //'hour'         '00-23'
            isbnVal = isbnVal + mins;                                          //'minutes'      '00-59'
            isbnVal = isbnVal + seconds;                                       //'second'       '00-59'

            $('#isbn').val(isbnVal);
            $('#genISBN').val(isbnVal);
            $('#isbn').click(function() { $(this).val(''); $('#genISBN').val(''); $(this).unbind(); });
        });
    }
});


