﻿
// I due to the overlap of some of the div's to get this to work correclty
// I used a global holder 
var cartHoldOpenTimer = 0;
function showCart() {
   // document.getElementById('cart_detail').style.display = 'block';
    $('#cart_detail').slideDown('normal');
    cartHoldOpenTimer = 1;
}
function holdCart() {
    cartHoldOpenTimer = 1;
}
function hideCart() {
    cartHoldOpenTimer = 0;
    
    setTimeout("hideCartNow()", 5000);
   //document.getElementById('cart_detail').style.display = 'none';
}
function hideCartNow() {
    if (cartHoldOpenTimer == 0) {
        $('#cart_detail').slideUp('normal');
    }
}
var dialogManager = {
    hideDiv: function(id) {
        $('#' + id).hide();
    }
}

/* NOT FINISHED */
function showDialog() {
    $("#dialog").dialog("destroy");
    $("#dialog").dialog({ modal: true });
    
}

function addToCart() {


    document.getElementById('customizeForm').submit();
    
      
}

function commuteData(quantitySelect) {
    document.getElementById('quantity').value =
        quantitySelect.options[quantitySelect.selectedIndex].value;
    updatePrice();
}

function showError(msg) {
    document.getElementById("errors").innerHTML = msg;
    document.getElementById("errors").style.display = "block";
}

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

function updatePrice() {
    var cart_id = document.getElementById('cart_id').value;
    var quantity = parseInt(document.getElementById('quantity').value);
    if (quantity == 'NaN' || quantity == 0) return;
    var opt = document.getElementById('paper_option_id');
    var opt_id = opt.options[opt.selectedIndex].value;
    var siz = document.getElementById('size_id');
    var size_id = siz.options[siz.selectedIndex].value;
    var yewrl = '/Ajax/GetPrice?cart_id=' + cart_id + '&opt_id=' + opt_id + "&quantity=" + quantity + "&size_id=" + size_id;
    var custOpt = document.getElementById('cust_opts');
    if (custOpt != null) {
        yewrl += '&cust_opts=';
        var opts = custOpt.value.split('|');
        for (i = 0; i < opts.length; i++) {
            if (document.getElementById('fop_' + opts[i]) == null) continue;
            if (document.getElementById('fop_' + opts[i]).checked) {
                yewrl += '|' + opts[i];
            }
        }
    }

    $.ajax({
        url: yewrl,
        dataType: 'json',
        cache: false,
        success: function(data) {
            if (data.exception != null && data.exception != "") {
                alert(data.exception);
                return;
            }
            var price = parseFloat(data.discountedPrice);
            if (document.getElementById('print_ready') != null
                && !document.getElementById('print_ready').checked)
                price += parseFloat(document.getElementById('not_print_ready_surcharge').value.substring(1));
            var priceText = '$' + price.toFixed(2);
            if (data.discountText != '') {
                document.getElementById('li_discount').style.display = 'block';
                document.getElementById('the_discount').innerHTML = data.discountText;
            } else {
                document.getElementById('li_discount').style.display = 'none';
            }
            document.getElementById('the_price').innerHTML = priceText;
            $.uniform.update();
        }
    });
}

function getQuantities() {
    var quantity = parseInt(document.getElementById('quantity').value);
    var quantities = document.getElementById('quantity_select');
    if (quantities == null) {
        updatePrice();
        return;
    }
    quantities.options.length = 0;
    var opt = document.getElementById('paper_option_id');
    var opt_id = opt.options[opt.selectedIndex].value;
    var siz = document.getElementById('size_id');
    var size_id = siz.options[siz.selectedIndex].value;
    $.ajax({
        url: '/Ajax/GetQuantitiesByPaperAndSize?paper_option_id=' + opt_id + '&product_size_id=' + size_id,
        dataType: 'json',
        cache: false,
        success: function(data) {
            if (data.exception != null && data.exception != "") {
                alert(data.exception);
                return;
            }
            var selected = 0;
            document.getElementById('quantity').value = data.list[0].quantity;
            for (i = 0; i < data.list.length; i++) {
                quantities.options[i] = new Option(data.list[i].title, data.list[i].quantity);
                if (quantity == data.list[i].quantity) {
                    selected = i;
                    document.getElementById('quantity').value = data.list[i].quantity;
                }
            }
            quantities.options[selected].selected = "selected";
            updatePrice();
            $.uniform.update();
        },
        error: function(data) {
        }
    });
}

    function refreshCartView() {
        $.ajax({
            url: '/Ajax/CartSummary/'+document.getElementById('cart_id').value,
            dataType: 'json',
            cache: false,
            success: function(data) {
                document.getElementById('cart_view').style.display = 'block';
                document.getElementById('cart_num_items').innerHTML = data.items.length;
                var cart_items = '<div id="cart_body"><table width="100%" cellpadding="5" cellspacing="0" border="0">';
                var total = 0;
                for (i = 0; i < data.items.length; i++) {
                    cart_items += '<tr><td class="white12">&nbsp;&nbsp;' + data.items[i].title + '</td><td class="white12">' + data.items[i].quantity + '</td></tr>';
                    total += data.items[i].quantity
                }
                //cart_items += '<tr><td>Total</td><td>' + total + '</td></tr>';
                cart_items += '<tr><td style="padding: 15px 0 0 15px;"><a class="cart_link" href="/Checkout"><span class="white14bold">Check&nbsp;Out</span></a></td></tr></table></div><div id="cart_foot"></div>';
                document.getElementById('cart_detail').innerHTML = cart_items;
                $.uniform.update();
            },
            error: function(data) {
            }
        });
    }

    function nav(igation) {
        $.ajax({
            url: igation + '?cart_id=' + document.getElementById('cart_id').value,
            dataType: 'html',
            cache: false,
            success: function(data) {
                document.getElementById('catalog').innerHTML = data;
                if (document.getElementById('up_file') != null) {
                    uploaderSetup();
                    if (document.getElementById('quantity_select') != null) {
                        getQuantities();
                    } else {
                        updatePrice();
                    }
                    $("select, input, input:checkbox, input:radio, input:file, input:text").uniform();
                    //tabs
				$(".tab_content").hide(); //Hide all content
				$("ul.tabs li:first").addClass("active").show(); //Activate first tab
				$(".tab_content:first").show(); //Show first tab content

				//On Click Event
				$("ul.tabs li").click(function() {
				$("ul.tabs li").removeClass("active"); //Remove any “active" class
				$(this).addClass("active"); //Add “active" class to selected tab
				$(".tab_content").hide(); //Hide all tab content

				var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
					activeTab = activeTab.split("#"); //bugfixed by droope :)
					$("#"+activeTab[activeTab.length-1]).fadeIn(); //Fade in the active ID content
				return false;
				});

                }
                $.uniform.update();
                //equalHeight($(".column"));
            }
        });
    }

     function whichBrs() {
        var agt = navigator.userAgent.toLowerCase();
        if (agt.indexOf("opera") != -1) return 'Opera';
        if (agt.indexOf("staroffice") != -1) return 'Star Office';
        if (agt.indexOf("webtv") != -1) return 'WebTV';
        if (agt.indexOf("beonex") != -1) return 'Beonex';
        if (agt.indexOf("chimera") != -1) return 'Chimera';
        if (agt.indexOf("netpositive") != -1) return 'NetPositive';
        if (agt.indexOf("phoenix") != -1) return 'Phoenix';
        if (agt.indexOf("firefox") != -1) return 'Firefox';
        if (agt.indexOf("safari") != -1) return 'Safari';
        if (agt.indexOf("skipstone") != -1) return 'SkipStone';
        if (agt.indexOf("msie") != -1) return 'Internet Explorer';
        if (agt.indexOf("netscape") != -1) return 'Netscape';
        if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
        if (agt.indexOf('\/') != -1) {
            if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
                return navigator.userAgent.substr(0, agt.indexOf('\/'));
            }
            else return 'Netscape';
        } else if (agt.indexOf(' ') != -1)
            return navigator.userAgent.substr(0, agt.indexOf(' '));
        else return navigator.userAgent;
    }
	
    function uploaderSetup() {
		 var uploadifySwf = '/Scripts/uploadify.swf';
		 
		if (whichBrs() == 'Internet Explorer') {
            uploadifySwf = 'http://upload.printpower.com/uploadifier/Scripts/uploadify.swf';
        }
	
        $('#up_file').uploadify({
            'uploader': uploadifySwf,
            'script': '/Ajax/UploadFile',
            'checkScript': '/Ajax/CheckFile',
			'allowscriptaccess': 'always',
            'scriptAccess': 'always',
            'scriptData': { 'cart_id': document.getElementById('cart_id').value },
            'cancelImg': '/Scripts/cancel.png',
            'wmode': 'transparent',
            'multi': true,
            'buttonImg': 'http://upload.printpower.com/uploadifier/Content/images/browse-button.png',
            'onComplete': function(event, QueueID, fileObj, response, data) {
                response = eval('('+response+')');
                if (data.exception == null)
                    document.getElementById('tmp_item_files').value += '|' + response.file_received;
                return true;
            },
            'onAllComplete': function(event, QueueID, fileObj, response, data) {
                processFiles();
		

                return true;
            },
            'onError': function(event, queueID, fileObj, errorObj) {
				alert(errorObj.type + ': ' + errorObj.info);
                showError(errorObj.type + ': ' + errorObj.info);
            }
        });
    }

    function processFiles() {
        var combo = "cart_id=" + escape(document.getElementById('cart_id').value);
        combo += "&product_id=" + escape(document.getElementById('product_id').value);
        combo += "&item_files=" + escape(document.getElementById('tmp_item_files').value);

var urlSpec = "/Ajax/ProcessFiles/" + Math.floor(Math.random()*11); 





        ErrorDialog.alldonewaiting();
        ErrorDialog.hurryupandwait('Processing Files');
        
        $.ajax({
            url: urlSpec,
            type: "POST",
            dataType: 'html',
            data: combo,
            cache: false,
            success: function(data) {
                ErrorDialog.alldonewaiting();
                $("#fancyfile").click();
                updatePrice();
                $.uniform.update();
		//alert(combo);
		//addToCart();

            },
            error: function(data, error) {
                ErrorDialog.updatemessage('System Error<br /><br />Please retry or contact a representative.<br /><br /><input type="button" onclick="ErrorDialog.alldonewaiting();" value="OK" />');
            }
        });
        return false;
    }

    function closeFancy() {
        $.fancybox.close();
        document.getElementById('tmp_item_files').value = '';
    }

    function acceptProof(file,sizeId) {
        var sizeSelect = document.getElementById('size_id');
        for (j = 0; j < sizeSelect.options.length; j++) {
            if (sizeSelect.options[j].value == sizeId) {
                sizeSelect.selectedIndex = j;
                setAlready = true;
            }
        }
        document.getElementById('item_files').value += '|' + file;
        $('<li class="filelist" id="' + file + '"></li>').appendTo('#file_list').html(
          ' <a href="javascript:removeFile(\'' + file + '\');"><img src="/Scripts/cancel.png" alt="remove" border="0"/></a>&nbsp;&nbsp;' + file);

        var inner = document.getElementById('tmp_item_files').value;
        var start = inner.indexOf(file);
        var end = start + file.length;
        document.getElementById('tmp_item_files').value =
        inner.substring(0, start) + inner.substring(end);

        updatePrice();
    }

    function acceptNPR(file) {
        document.getElementById('print_ready').value = '0'; 
        document.getElementById('item_files').value += '|' + file;
        $('<li class="filelist" id="' + file + '"></li>').appendTo('#file_list').html(
          ' <a href="javascript:removeFile(\'' + file + '\');"><img src="/Scripts/cancel.png" alt="remove" border="0"/></a>&nbsp;&nbsp;' + file);

        var inner = document.getElementById('tmp_item_files').value;
        var start = inner.indexOf(file);
        var end = start + file.length;
        document.getElementById('tmp_item_files').value =
        inner.substring(0, start) + inner.substring(end);

        updatePrice();
    }

    function removeFile(file) {
        var inner = document.getElementById('item_files').value;
        var start = inner.indexOf(file);
        var end = start + file.length;
        if (start > -1) {
            document.getElementById('item_files').value =
            inner.substring(0, start) + inner.substring(end);
        }

        inner = document.getElementById('tmp_item_files').value;
        start = inner.indexOf(file);
        end = start + file.length;
        if (start > -1) {
            document.getElementById('tmp_item_files').value =
            inner.substring(0, start) + inner.substring(end);
        }

        inner = document.getElementById('file_list').innerHTML;
        start = inner.indexOf('<li id="' + file);
        end = inner.indexOf('</li>', start) + 5;
        if (start > -1) {
            document.getElementById('file_list').innerHTML =
            inner.substring(0, start) + inner.substring(end);
        }
        
        var files = document.getElementById('item_files').value.split('|');
        for (i = 0; i < files.length; i++) {
            if (files[i] != '') {
                return;
            }
        }
        document.getElementById('print_ready').value = '1';
    }


    function addAddressBlock(data, name, type, onclick) {
        if (onclick) {
            var click = " onClick=\"" + onclick + "\"";
        } else {
            var click = "";
        }


        var newLi = '<li style="float:left;">';
        newLi += '    <div id="nAddrBox_' + data.id + '" style="display:none" class="addressHoldingBox">';
        newLi += '                        <div class="addressHeader">';
        newLi += '                             <div style="float:left; display:block;"><input class="noborder" type="radio" name="' + type + '_id" value="' + data.id + '" ' + click + ' /></div>';
        newLi += '                             <div style="padding:2px; float:left; display:block;">' + name + '</div>';
        newLi += '                              <div class="clear"></div>';
        newLi += '                          </div>';
        newLi += '                              ';
        newLi += '                         <div class="address">';
        newLi += '                           ' + data.street1 + '<br />';
        if (data.street2 != '') {
            newLi += '                           ' + data.street2 + '<br />';
        }
        newLi += '                           ' + data.city + ', ' + data.state + ', ' + data.zipcode;
        if (data.street2 == '') {
            newLi += '                           <br />';
        }
        newLi += '                      </div>';
        newLi += '                  <a href="javascript:editAddress(\'' + data.id + '\');">Edit</a>';
        newLi += '                  </div>';
        newLi += '            </li>';

        //alert(newLi);
        return newLi;
    }


    function addressDiv(data, name, type, onclick) {
        if (onclick) {
            var click = " onClick=\"" + onclick + "\"";
        } else {
            var click = "";
        }


        newLi =  '                        <div class="addressHeader">';
        newLi += '                             <div style="float:left; display:block;"><input class="noborder" type="radio" name="' + type + '_id" value="' + data.id + '" ' + click + ' /></div>';
        newLi += '                             <div style="padding:2px; float:left; display:block;">' + name + '</div>';
        newLi += '                              <div class="clear"></div>';
        newLi += '                          </div>';
        newLi += '                              ';
        newLi += '                         <div class="address">';
        newLi += '                           ' + data.street1 + '<br />';
        if (data.street2 != '') {
            newLi += '                           ' + data.street2 + '<br />';
        }
        newLi += '                           ' + data.city + ', ' + data.state + ', ' + data.zipcode;
        if (data.street2 == '') {
            newLi += '                           <br />';
        }
        newLi += '                      </div>';
        newLi += '                  <a href="javascript:editAddress(\'' + data.id + '\');">Edit</a>';

        return newLi;
    }


function CheckProductForm() {

    var r = true;

    if ($('#quantity').val() < 1) {
        $('#producterror').html("Please select a quantity.");
        $('#producterror').fadeIn('normal');
        $('#quantity').focus();
        r = false;
    }

    if (uploadedFileExists() == false) {
        $('#producterror').html("Please upload a file.");
        $('#producterror').fadeIn('normal');
        r = false;
    }


    return r;
}

function uploadedFileExists() {
    var files = document.getElementById('item_files').value.split('|');
    for (i = 0; i < files.length; i++) {
        if (files[i] != '') {
            return true;
        }
    }
    return false;
}

var ErrorDialog = {
    hurryupandwait: function(msg) {

        var elm = $('<div id="huaw"></div>');
        elm.html('<p style="padding: 5px">' + msg + '</p><p style="padding: 5px">Please Wait...</p> <p style="padding:5px"><img alt="" src="Content/images/pleasewait.gif"/></p>');
        elm.dialog({ title: "Please Wait", autoOpen: false, draggable: false, modal: true });
        elm.dialog('open');
    },
    alldonewaiting: function() {
        $('#huaw').remove();
    },
    updatemessage: function(msg) {
        $('#huaw').html(msg);
    },
    alert: function(msg) {
        var elm = $('<div id="huaw" style="text-align:left"></div>');
        elm.html(msg);
        elm.dialog({
            title: '<img alt="" src="/Content/images/sign_warning.png"/>&nbsp;Notice',
            autoOpen: false,
            draggable: false,
            modal: false,
            buttons: { "Ok": function() { $(this).dialog("close"); } }
        });
        elm.dialog('open');
    }
}

