
    $.fn.disable = function(productid) {

        if($(this).attr('id')){
        var but = $(this).attr('id').indexOf('addtobasketbutton');
        var opt = $(this).attr('id').indexOf('option');
        var cus = $(this).attr('id').indexOf('custom');
        productid = $(this).attr('id').substr(0,(opt>-1 ? opt : (cus>-1 ? cus : but)));
        } else { productid = -1; }

        if(optstock[productid]){
            if(!prodbackor[productid] || (prodbackor[productid] && optstock[productid])){
                this.disableSel(productid);
            }else{
                return this.addClass('disabled');
            }
        }
        return this;
    }

    $.fn.enable = function(productid) {
        optid = $(this).attr('id');
        if(optid){
        var but = $(this).attr('id').indexOf('addtobasketbutton');
        var opt = $(this).attr('id').indexOf('option');
        var cus = $(this).attr('id').indexOf('custom');
        productid = $(this).attr('id').substr(0,(opt>-1 ? opt : (cus>-1 ? cus : but)));
        } else { productid = -1; }

        if(optstock[productid]){
            if(!prodbackor[productid] || (prodbackor[productid] && optstock[productid])){
                this.enableSel(productid);
            }else{
                return this.removeClass('disabled');
            }
        }
        return this;
    }

    $.fn.enableItem = function() {
       return $(this).removeClass('disabled').attr('disabled',false);
    }

    $.fn.disableItem = function() {
       return $(this).addClass('disabled').attr('disabled',true);
    }

    $.fn.disableSel = function() {
        if($(this).attr('id')){
        var but = $(this).attr('id').indexOf('addtobasketbutton');
            if(but>-1){
                but = (but>-1 ? -($(this).attr('id').length - 17) : -1);
                productid = $(this).attr('id').substr(17);
            }
            
            var opt = $(this).attr('id').indexOf('option');
            var cus = $(this).attr('id').indexOf('custom');
            productid = (productid ? productid : $(this).attr('id').substr(0,(opt>-1 ? opt : (cus>-1 ? cus : 0))));

        } else { productid = -1; }

        if(optstock[productid]){
            return this.attr('disabled', true).addClass('disabled');
        }
        return this;
    }

    $.fn.enableSel = function() {
         optid = $(this).attr('id');
        if(optid){
        var but = $(this).attr('id').indexOf('addtobasketbutton');
        var opt = $(this).attr('id').indexOf('option');
        var cus = $(this).attr('id').indexOf('custom');
        productid = $(this).attr('id').substr(0,(opt>-1 ? opt : (cus>-1 ? cus : but)));
        } else { productid = -1; }


        if(optstock[productid]){
           return this.attr('disabled', false).removeClass('disabled');
        }
        return this;
    }

    $.fn.resetSel = function(){

        if($(this).attr('id')){
        var but = $(this).attr('id').indexOf('addtobasketbutton');
        var opt = $(this).attr('id').indexOf('option');
        var cus = $(this).attr('id').indexOf('custom');
        productid = $(this).attr('id').substr(0,(opt>-1 ? opt : (cus>-1 ? cus : but)));
        } else { productid = -1; }

        if(optstock[productid]){
            if($(this).children('[selected=true]').attr('id')){
                $(this).siblings().find('[id="' + $(this).children('[selected=true]').attr('id').replace('item','custom') + '"]').disableSel();
            }

            $(this).disableSel();
        }
        $(this).find('option:first').attr('selected', 'selected');
        return this;
    }

$(function(){

    //if($('.productBasketInner').size()>0){
    $('.productBasketInner').each(function(){
        $(this).find('select').resetSel();
        $(this).find('input[type="text"][id*="custom"],textarea[id*="custom"]').val("").disableSel();
        $(this).find('select:first').enableSel().change();
        disableButton();
    });//}

    //if($('.lone')){
    $('.lone').each(function(){
        if($(this).attr('title')!="Custom"){            
            $(this).Watermark($(this).attr('title'));
        }
    });
    //}

});

// The Update Quantity Function
function updateQuantity(prodid){

    stocklevel = check_stock_level(prodid);
    var req = required_selects(prodid);

    if( stocklevel ){
        if (req) {showstockresult(prodid, stocklevel);}
    }else{
        if (req) {showstockresult(prodid, 0);}
    }
}

// Disable the add to basket button
function disableButton(productid) {
    $('#addtobasketbutton' + productid).disableSel();
    $('#addtobasketbutton' + productid + '[type="image"]').css('opacity','1').css('cursor','pointer');
    $('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop');
    $('#addtobasketbutton' + productid + '.disabled[type="image"]').css('opacity','0.5').css('cursor','no-drop');
}

// Disable the add to basket button
function enableButton(productid) {
    $('#addtobasketbutton' + productid).enableSel();
    $('#addtobasketbutton' + productid + '[type="image"]').css('opacity','1').css('cursor','pointer');
}

// This returns a stock level based on the combination of selects
function check_stock_level(productid) {
    var stock_level = 0;
    var dt = JSON.stringify(window['data' + productid]); var dat = JSON.parse(dt);

    var stockrecordid = 0;

    if (optstock[productid] == 1){

        if(dat.stock){

            // Loop through all stock records
            $.each(dat.stock, function(key, record){

                stockrecordid = record['stockid'];

                // Loop through all of the select boxes
                $('.productOptions' + productid).find('select').each(function(){

                    var optionid = $(this).attr('id').replace(productid + 'option','');
                    var itemid = $(this).children('[selected=true]').attr('id').replace(productid + 'item','');
                    var isrequired = dat.options[optionid].isrequired;
                    var stock_based = dat.options[optionid].stock_based;
                    
                    if ( key > -1 ){

                        var stockitem = dat.stock[key].items[optionid];

                        // If the selected option item f(i.e. 'Blue') is in the current stock record
                        if (stockitem==itemid || (isrequired == false && !itemid) || !stockitem) {

                            // Set the stock level - then continue to check the other selects
                            stock_level = record.qty;

                        }else{

                            // This option isnt in the stock record so set stock level to 0

                            stock_level = 0;
                            stockrecordid = "";
                            return false; // Skip this loop, so it goes on to check the next stockrecord
                        }
                    }

                });

                // If it's gone through all of the selects and stock_level still has a value, then break out and return it.
                if (stock_level > 0) {  return false; }

            });
        }else{
            stock_level = 0;
        }

        if(stockrecordid){
            $('#stockrecord' + productid).val(stockrecordid);
        }
    }else{
        stock_level = pstck[productid];
    }


    return stock_level;
}


function required_selects(productid){

    var dt = JSON.stringify(window['data' + productid]); var dat = JSON.parse(dt);
    var ok = false;


    if($('.productOptions' + productid).find('select').size()>0){

        // Loop through all of the product options
        $('.productOptions' + productid).find('select').each(function(){

            var isrequired = dat.options[$(this).attr('id').replace(productid + 'option','')].isrequired;
            var theid = $(this).attr('id');
            var val = $(this).val();
            
            var itemid = $(this).children('[selected=true]').attr('id').replace(productid + 'item','');
            
            // If there is one without a value and it is required, return false
            if ( val == "" && isrequired == 1){

                ok = false;
                return false;

            }else{

                ok = true;

                var custom = $('#' + productid + 'custom' + itemid);
               
                if(custom.length){
                    var customVal = $(custom).val();
                    var watermark = $(custom).attr('title')

                    // Check custom fields
                    if ( isrequired == 1 && $('#' + productid + 'custom' + itemid ).parent().css('display') != 'none' && ( !customVal || customVal.length<=0 || customVal == watermark )){
                        ok = false;
                        return false;
                    }
                }

            }

        });

    }else{
        ok = true;
    }

    return ok;

}

$.fn.selectRange = function(start, end) {
        return this.each(function() {
                if(this.setSelectionRange) {
                        //this.focus();
                        this.setSelectionRange(start, end);
                } else if(this.createTextRange) {
                        var range = this.createTextRange();
                        range.collapse(true);
                        range.moveEnd('character', end);
                        range.moveStart('character', start);
                        range.select();
                }
        });
};

function limitChars(el, limit, infodiv)
{
    var text = $(el).val();

    var textlength = text.length;

    if(textlength > limit)
    {
        $(infodiv).html('You cannot write more then '+limit+' characters.');

        $(el).val(text.substr(0,limit));

        return false;
    }
    else
    {
        $(infodiv).html((limit - textlength) +' characters left.');

        return true;
    }
}

function DOMReload(productid){

    var dt = JSON.stringify(window['data' + productid]); var dat = JSON.parse(dt);

    // make any disabled image buttons opaque
    $('#addtobasketbutton' + productid + '[type="image"]').css('opacity','1').css('cursor','pointer');
    $('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop');

    var currentTyping;

    // Fire this thing's change event on keyup
    $('.productOptions' + productid).find('select').keyup(function(){
        $(this).change();
    });

    // Loop through the custom fields
    $('input[id^="' + productid + 'custom"],textarea[id^="' + productid + 'custom"]').keyup(function(){

        if ( $(this).val().length<=0 ) {
            $(this).attr('typed',false);
        }

        if ( $(this).attr('typed') ){
            return false;
        }

        currentTyping = $(this);

        var Selected = $(this).parent().siblings('select');

        $(Selected).change();

        // If there the stock count is larger than 0 or backordering is on, show message and button
        var stock_level = check_stock_level(productid);
        if(optstock[productid]) {
        $('#stocklevel' + productid).html('');
        }

        if(prodbackor[productid]){
            var req = required_selects(productid);

            if (stock_level <= 0 && req){
                showstockresult(productid, stock_level);
            }
        } 


                $('#addtobasketbutton' + productid).disableSel();
        // make any disabled image buttons opaque
        $('#addtobasketbutton' + productid + '[type="image"]').disableSel();
        $('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop');
        
        if (stock_level > 0 || '1' == prodbackor[productid] || '0' == '1' ) {
            var req = required_selects(productid);

            if (req) {

                showstockresult(productid,stock_level); // Enable the button because there was stock of this combination.

            }
        }

        if( $(this).val().length > 0 ) {
            $(this).attr('typed',true);
        }else{
            $(this).attr('typed',false);
        }
    });


    // The change event for selects fires checks against the stock to
    $('.productOptions' + productid).find('select').change(function(){

        var custom = false;

        // The current select's index, current option and current item in the group
        var CurrentSelectIndex = $(this).attr('rel');
        var optionid = $(this).attr('id').replace(productid + 'option','');
        var itemid = $(this).children('[selected=true]').attr('id').replace(productid + 'item','');

        // The selected item's id
        var selected = $(this).children('[selected="true"]').attr('id');

	// Total the price with the selected options
        updateprice(productid, "addtobasket" + productid,selected);

        
            // Disable all the items within the following options (except default ones);
            if(optstock[productid]){    
                sdo = false;
                
                // get the id of the option and see if it's a stock dependant option before disabling the items
                nextoptid = $('.productOptions' + productid).find('select:gt(' + (CurrentSelectIndex-1) + '):visible').attr('id');
                
                if(nextoptid != undefined) {
                    nextopt = nextoptid.replace(productid + 'option','');
                    // loop through the stock records to see if it's in there
                    $.each(dat.stock,function(key,sr){
                        if(sr.items  != undefined && sr.items[nextopt] != undefined) { sdo = true; }
                    });
                }
                
                if(sdo) {
                    $('.productOptions' + productid).find('select:gt(' + (CurrentSelectIndex-1) + '):visible').children('option[value!="none"][value!=""]').disableItem();
                }
           }
        

        // Hide all of the custom fields for this option
        var tempitem = selected.substr(0,selected.indexOf('item')+4).replace('item','custom');
        if(tempitem){
            $(this).siblings().find('[id^="' + tempitem + '"][id!="' + $(this).children('[selected=true]').attr('id').replace('item','custom') + '"]').parent().hide();
        }

        if( $(this).val() == "" ){
            $(this).siblings().find('[id*="custom"]').parent().hide();
        }

        // If there's a custom field for the current option, show it
        if(itemid){
            $('#' + ($(this).children('[selected=true]').attr('id').replace('item','custom') ? $(this).children('[selected=true]').attr('id').replace('item','custom') : "NotFound")).enableSel().parent().show();
        }


        // -- If none or choose has been selected, and the option is required, disabled the rest.
        if (( $(this).val() == "none" || $(this).val() == "" ) && (dat.options[optionid].isrequired == 1)){

            // Disable all selects AND custom fields that occur AFTER the current one
            $('.productOptions' + productid).find('select:gt(' + (CurrentSelectIndex-1) + ')').disableSel();
            $('.productOptions' + productid).find('select:gt(' + (CurrentSelectIndex-1) + ')').each(function(){
                $('#' + ($(this).children('[selected=true]').attr('id').replace('item','custom') ? $(this).children('[selected=true]').attr('id').replace('item','custom') : "NotFound")).disableSel();
            });

            // Disable the ad to basket button / image
            disableButton(productid);
        }


        // -- If there the stock count is larger than 0 or the stock_control_out is set to backorder, show message and button
            var stock_level = check_stock_level(productid);
            if(optstock[productid]) {
                // Clear the stock level box html
                $('#stocklevel' + productid).html('');
            }

                            // Temporarily disable the button
                disableButton(productid);

                var req = required_selects(productid);

                // If stock level is 0 then show the result.
                if (stock_level <= 0 && req){
                    showstockresult(productid, stock_level);
                }
            
            // if in stock, or back ordering allowed, or stock control off..
            if (stock_level > 0 || '1' == prodbackor[productid] || '0' == '1' ) {

                // Check all the required selects are set
                var req = required_selects(productid);

                // If they are set, then show the result
                if (req) {
                    showstockresult(productid, stock_level); // Enable the button because there was stock of this combination.
                }
            }

        // Current select's value
        var CurrentVal = $(this).val();

        // Current select's value array
        var SelectedAr = CurrentVal.split("|");
        var CurrentCustomID = '#' + productid + 'custom' + SelectedAr[2];
      
        // Get custom field value
        if($(CurrentCustomID).attr('id')) {
            var CustomValue = $('#' + productid + 'custom' + SelectedAr[2]).val().length;
        }
        
        // if something other than the [Choose] option has been selected plus if there is a custom field, it has a value
        if ((CurrentVal == "none" && dat.options[optionid].isrequired != 1) || (CurrentVal != '' && CurrentVal != 'none') && ( ($(CurrentCustomID).val()=='undefined' ) ||  ($(CurrentCustomID).val()!='undefined' &&  CustomValue != 0)) ){
            
                        // Otherwise look through all of the stock records where this the selected value exists
            // and enable the relative options in the following selects.
            // Loop through all stock records

            if (dat.stock){
                $.each(dat.stock, function(key, record){
                    // Reset the stock level
                    var stock_level = 0;

                    // Loop through all of the select boxes
                    $('.productOptions' + productid).find('select').each(function(){

                        // Get the select details
                        var optionid = $(this).attr('id').replace(productid + 'option','');
                        var itemid = $(this).children('[selected=true]').attr('id').replace(productid + 'item','');
                        var isrequired = dat.options[optionid].isrequired;

                        // If key is a number (i.e. not 'count')
                        if ( key > -1 ){

                            // If the selected option item (i.e. 'Blue') is in the current stock record
                            var stockitem = dat.stock[key].items[optionid];
                            if ( stockitem == itemid || (isrequired == false && !itemid) || !stockitem || ( $(this).attr('disabled') != false ) ) {
                               
                                // Set the stock level - then continue to check the other selects
                                stock_level = record.qty;
                                return false;

                            }else{

                                // This option isnt in the stock record so set stock level to 0
                                stock_level = 0;
                                return false; // Skip this loop, so it goes on to check the next stockrecord

                            }

                            
                            // If not stockitem - so if not in the stock record
                            if( !stockitem ) {
                            	// Loop through all the stock
                                $.each(dat.stock, function(x, xrecord){
                                    if ( x > -1 ){
                                    	// enable the options
                                        tmpid = '#' + productid + 'item' + dat.stock[x].items[optionid];
                                        $(tmpid).enable();
                                    } 
                                });
                            }
                        }

                        
                    });

                    

                    // If it's gone through all of the selects and stock_level still has a value, then break out and return it.
                    if (stock_level > 0) {
                        // Enable the available items
                        $.each(dat.stock[key].items, function(ikey, irecord){
                           tmpid = '#' + productid + 'item' + dat.stock[key].items[ikey];
                           $(tmpid).enableItem();
                        });
                    }
                });
            }
            

                        

            // -- Enable the next required select
            	// loop through all selects
                $('.productOptions' + productid).find('select:gt(' + (CurrentSelectIndex-1) + ')').each(function(){

                    // If this is the select after the changed one
                    var thisindex = $(this).attr('rel');
                    var nextindex = parseInt(CurrentSelectIndex) + 1;

                    // If this is the next select
                    if (thisindex == nextindex){

                    	// Get the details of he select
                        var selecteditem = $(this).children('[selected=true]');
                        var selecteditemdisabled = $(selecteditem).attr('disabled');
                        var selecteditemvalue = $(selecteditem).val();

                        // Enable it (and the custom field if there is one)
                        $(this).enableSel();
                        $('#' + ($(this).children('[selected=true]').attr('id').replace('item','custom') ? $(this).children('[selected=true]').attr('id').replace('item','custom') : "NotFound") ).enableSel();

			// if the select was currently disabled
                        if (selecteditemdisabled == true){
                            // Reset the select to it's default
                            if($(this).children('option').size()>2){
                               $(this).find('option:first').attr('selected', 'selected').change();
                            }

                        }else{

                            // Otherwise, show the custom field if there is one?
                            $('#' + ($(this).children('[selected=true]').attr('id').replace('item','custom') ? $(this).children('[selected=true]').attr('id').replace('item','custom') : "NotFound") ).enableSel().parent().show();

                        }


                    }

                    // Get the option id
                    var optionid = $(this).attr('id').replace(productid + 'option','');

                    // Current select's value
                    var CurrentVal2 = $(this).val();

                    // Current select's value array
                    var SelectedAr2 = CurrentVal.split("|");

                    // Get custom field value
                    if($('#' + productid + 'custom' + SelectedAr2[2]).attr('id')) {
                        var CustomValue2 = $('#' + productid + 'custom' + SelectedAr2[2]).val().length;
                    }

                    // If this is not a required field, loop back through
                    if(optionid>-1){
                        if ( (dat.options[optionid].isrequired == 0 && $(this).val() != "" && (( !CustomValue2 ) ||  ($('#' + productid + 'custom' + SelectedAr2[2]) &&  CustomValue2>0))) || ($('.productOptions' + productid).find('select:nth(' + $(this).attr('rel')+1 + ')').val()) || (dat.options[optionid].isrequired == 1 && $(this).val())){

                            // set this one to the current
                            CurrentSelectIndex = $(this).attr('rel');

                        }else{
                            return false;
                        }
                    }

                });

        }
      

        return false;

    });



}


function showstockresult(productid, stocklevel){

                    if(stocklevel<=0){
               if(prodbackor[productid]>0){
               
if (required_selects(productid)) {
     $('#stocklevel'+productid).html('<div style="display: inline-block;  color:#333333;">' + (oosmessage[productid] ? oosmessage[productid] : 'Out Of Stock!</div>'));

     $('button #addtobasketbutton'+productid+ ' span span').text('Add To Basket'); $('#addtobasketbutton'+productid).attr('title','Pre-Order this out of stock product.').attr('disabled','');

     $('#addtobasketbutton' + productid + '[type="image"]').css('opacity','1').css('cursor','pointer'); $('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop')
  }
} else  {

 $('#stocklevel'+productid).html('<div style="display: inline-block; color:#333333;">' + (oosmessage[productid] ? oosmessage[productid] : 'Out Of Stock!</div>'));

 $('button #addtobasketbutton'+productid+ ' span span').text('Out of Stock'); $('#addtobasketbutton'+productid).disableSel().attr('title','Product is out of stock!');


                        
$('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop');
                        
disableButton(productid);
}            }else{
                qty = $('#qty' + productid).val();
                if((stocklevel - qty) < 0 ){
                    if(prodbackor[productid]){
                   
$('#stocklevel' + productid).html('<div style="display: inline-block;  color:#333333;">There are ' + (stocklevel>0 ? 'only ' + stocklevel : '0') + ' of this product in stock. Please reduce your quantity or add to basket to back-order remaining items.</div>');

 $('button #addtobasketbutton'+productid+ ' span span').text('Add To Basket'); $('#addtobasketbutton' + productid).attr('title','Pre-Order this out of stock product.').attr('disabled','');

$('#addtobasketbutton' + productid + '[type="image"]').css('opacity','1').css('cursor','pointer').removeClass('disabled');
                            
$('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop');
}else{

disableButton(productid);
$('#stocklevel' + productid).html('<div style="display: inline-block;  color:#333333;">There are only ' + (stocklevel>0 ? stocklevel : '0') + ' of this product in stock. Please reduce your quantity.</div>');

 $('button #addtobasketbutton'+productid+ ' span span').text('Out of Stock'); $('#addtobasketbutton' + productid).disableSel().attr('title','Product is out of stock!');

// make any disabled image buttons opaque
                        
$('#addtobasketbutton' + productid + '[type="image"]').css('opacity','1').css('cursor','pointer');
                        
$('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop');
                         
disableButton(productid);                    }
                }else{
            
$('#stocklevel' + productid).html(stocklevel + ' in stock.');
                    $('button #addtobasketbutton'+productid+ ' span span').text('Add To Basket');
                    $('#addtobasketbutton' + productid).attr('title','').attr('disabled','');
                    $('#addtobasketbutton' + productid + '[type="image"]').css('opacity','1').css('cursor','pointer').removeClass('disabled');
                    $('#addtobasketbutton' + productid + '[type="image"][disabled="true"],' + '#addtobasketbutton' + productid + '[type="image"][disabled="disabled"]').css('opacity','0.5').css('cursor','no-drop');
                    $('input.disabled[type="image"]').css('opacity','0.5').css('cursor','no-drop');
                
                 }

            }

       
}


function updateprice(productid, form, element) {

    var prodprice = parseFloat($('#'+form+' input[name=unit_price]').val());

    $('#' + form).find('select').each(function(){
        var tcustomval = true;

        var tcustom = $(this).find('option:selected').attr('id').replace(/item/,'custom');
        if(tcustom && $('#' + tcustom).size()){
            tcustomval = $('#' + tcustom).val();
            if($.trim(tcustomval) == $.trim($('#' + tcustom).attr('title'))){
                tcustomval = '';
            }
        }

        var tval = $(this).val();
        if(tval != "" && tval != "none" && tcustomval){
            re = /^.*\|([0-9\.-]+)\|.*$/;
            re.exec(tval);
            prodprice = prodprice + parseFloat(RegExp.$1);
        }

    });


    prodprice = Math.round(prodprice * 100) / 100;
    prodprice = (prodprice + 0.001) + '';
    $('.prodpriceeach' + productid).html(prodprice.substring(0, prodprice.indexOf('.') + 3));
    document.getElementById('prodpriceeach' + productid).innerHTML = prodprice.substring(0, prodprice.indexOf('.') + 3);

    return true;

}

function addbasketgo(productid, form) {


    if (!required_selects(productid)) {
        alert('Please fill in all required fields before clicking \"Add To Basket\"');
        return false;
    }

   // any customs that are still their watermark should be emptied
    $('input[id*="custom"],textarea[id*="custom"]').each(function(){
        if($(this).val() == $(this).attr('title')){
            $(this).val('');
        }
    });

    // any empty custom fields should have their select boxes set to "none"
    $('input[id*="custom"],textarea[id*="custom"]')
        .filter(function(){
            return ($(this).parent().css('display')=='block');
        })
        .each(function(){
        if($(this).val()==""){
            $('#' + $(this).attr('id').replace('custom','item')).val('none').parent().resetSel();
        }
    });


            // If backordering is off and the stock level is 0 then return false
    if (!prodbackor[productid]){
        if(pstck[productid]-$('#qty' + productid).val()<0){
            alert('There are only ' + (stocklevel>0 ? stocklevel : '0') + ' of this product in stock. Please reduce your quantity.');
            return false;
        } else if($('#qty' + productid).val()==0){
            alert("You must choose a quantity larger than 0");
            return false;
        }
    }
    
    return true;
}

function cursorPosition(el) {
    var textarea = document.getElementById(el);
    //textarea.focus();

    // get selection in firefox, opera, …
    if (typeof(textarea.selectionStart) == "number")

    {
        return textarea.selectionStart;

    } else if (document.selection) {
        var selection_range = document.selection.createRange().duplicate();

        if (selection_range.parentElement() == textarea) {
            // Check that the selection is actually in our textarea
            // Create three ranges, one containing all the text before the selection,
            // one containing all the text in the selection (this already exists), and one containing all
            // the text after the selection.
            var before_range = document.body.createTextRange();
            before_range.moveToElementText(textarea);
            // Selects all the text
            before_range.setEndPoint("EndToStart", selection_range);
            // Moves the end where we need it
            var after_range = document.body.createTextRange();
            after_range.moveToElementText(textarea);
            // Selects all the text
            after_range.setEndPoint("StartToEnd", selection_range);
            // Moves the start where we need it
            var before_finished = false,
            selection_finished = false,
            after_finished = false;
            var before_text,
            untrimmed_before_text,
            selection_text,
            untrimmed_selection_text,
            after_text,
            untrimmed_after_text;

            // Load the text values we need to compare
            before_text = untrimmed_before_text = before_range.text;
            selection_text = untrimmed_selection_text = selection_range.text;
            after_text = untrimmed_after_text = after_range.text;

            // Check each range for trimmed newlines by shrinking the range by 1 character and seeing
            // if the text property has changed. If it has not changed then we know that IE has trimmed
            // a \r\n from the end.
            do {
                if (!before_finished) {
                    if (before_range.compareEndPoints("StartToEnd", before_range) == 0) {
                        before_finished = true;
                    } else {
                        before_range.moveEnd("character", -1)
                        if (before_range.text == before_text) {
                            untrimmed_before_text += "\r\n";
                        } else {
                            before_finished = true;
                        }
                    }
                }
                if (!selection_finished) {
                    if (selection_range.compareEndPoints("StartToEnd", selection_range) == 0) {
                        selection_finished = true;
                    } else {
                        selection_range.moveEnd("character", -1)
                        if (selection_range.text == selection_text) {
                            untrimmed_selection_text += "\r\n";
                        } else {
                            selection_finished = true;
                        }
                    }
                }
                if (!after_finished) {
                    if (after_range.compareEndPoints("StartToEnd", after_range) == 0) {
                        after_finished = true;
                    } else {
                        after_range.moveEnd("character", -1)
                        if (after_range.text == after_text) {
                            untrimmed_after_text += "\r\n";
                        } else {
                            after_finished = true;
                        }
                    }
                }

            }
            while ((!before_finished || !selection_finished || !after_finished));

            // Untrimmed success test to make sure our results match what is actually in the textarea
            // This can be removed once you’re confident it’s working correctly
            var untrimmed_text = untrimmed_before_text + untrimmed_selection_text + untrimmed_after_text;
            var untrimmed_successful = false;
            if (textarea.value == untrimmed_text) {
                untrimmed_successful = true;
            }
            // ** END Untrimmed success test
            var startPoint = untrimmed_before_text.length;
            return startPoint;

        }
    }
    return startPoint;
}


