﻿var currentTab = '#design';
var theSwitch;
var viewedPreview = false;
var showPreview = false;
var breakLoop = false;

$(document).ready(function() {
    $("#theRTEdesigner").resizehandle();
    $('a.bold,a.left,a.center').cluetip({ splitTitle: '|', cluetipClass: 'jtip', arrows: true, fx: { open: 'fadeIn', openSpeed: 'slow' }, dropShadow: true });
    $('a.image').cluetip({ activation: 'hover', closePosition: 'title', sticky: true, splitTitle: '|', cluetipClass: 'jtip', arrows: true, fx: { open: 'fadeIn', openSpeed: 'slow' }, dropShadow: true });
    $('#priceLink').cluetip({ splitTitle: '|', cluetipClass: 'jtip', arrows: true, fx: { open: 'fadeIn', openSpeed: 'slow' }, dropShadow: true });
});

function selTab(num) {
    var theFrame = document.getElementById('theRTEdesigner');
    
    css = "<style type=\"text/css\">";
    css += "body{font-family:Arial;}p{margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;}\n";
    css += "img{max-width:180px;max-height:270px;border:none;width:180px;}\n";
    css += "</style>";
    theFrameDoc = "<html><head>" + css + '</head><body class="frameBody">' + $('#theLivePreview .classbox').html() + "</body></html>";

    theFrame.contentWindow.document.open();
    theFrame.contentWindow.document.write(theFrameDoc);
    theFrame.contentWindow.document.close();

    var iFrameDoc = $(theFrame.contentWindow.document);
    iFrameDoc.unbind();
    iFrameDoc.mousedown(function() {
        showLivePreview();
    });
    
    switch (num) {
        case 0:
            $('#lkDesign').click();
            break;
        case 1:
            $('#lkSchedule').click();
            break;
        case 2:
            $('#lkPreview').click();
            break;
        case 3:
            $('#lkOrder').click();
            break;
        default:
            alert('Unknown tab #' + num);
    }
}
function showRates(){
	var link = $('#showRates');
	var linkOffset = link.offset();
	brevTop = linkOffset.top - $('#divRates').height() - 1;
	
	$('#divRates').css("top", brevTop + "px").css("left", linkOffset.left + 1);
	
    if($('#divRates').is(':visible')){
        $('#divRates').fadeOut('normal');
		$('#hideRates').fadeOut('normal');
    }
    else{
        $('#divRates').fadeIn('normal');
		$('#hideRates').fadeIn('normal');
    }
}
function showCats() {
	if ($('#divCats').is(':visible')) {
        $('#divCats').fadeOut('normal');
		$('#hideCats').fadeOut('normal');
    }
    else {
        $('#divCats').fadeIn('normal');
		$('#hideCats').fadeIn('normal');
    }
    var link = $('#showCats');
    var linkOffset = link.offset();
    brevTop = linkOffset.top - $('#divCats').height() - 21;
    $('#divCats').css("top", brevTop + "px").css("left", "15px");
}
function showAbbrevs(){
	var link = $('#showBrev');
	var linkOffset = link.offset();
	brevTop = linkOffset.top - $('#divAbbrevs').height() - 31;
	$('#divAbbrevs').css("top", brevTop + "px").css("left", linkOffset.left + 1);
	
    if($('#divAbbrevs').is(':visible')){
        $('#divAbbrevs').fadeOut('normal');
		$('#hideBrev').fadeOut('normal');
    }
    else{
        $('#divAbbrevs').fadeIn('normal');
		$('#hideBrev').fadeIn('normal');
    }
}
function showHide(id){
    if ($(id).is(':visible'))
    {
        $(id).fadeOut('normal');
    }
    else
    {
        $(id).fadeIn('normal');
    }
}

function selectRate(rate, id)
{
    $('#theRate').text(' - ' + rate);
    $('#theRate').attr("val_id", id);
	showRates();
}
function selectSec(section, id, free)
{
    if (free == 0) {
        $('#showHideRates').fadeIn('slow');
        $('#theSection').attr("free", 0);
        document.getElementById(uc_payCredit).checked = true;
    }
    else if (free == 1) {
        $('#showHideRates').hide();
        $('#theSection').attr("free", 1);
        $('#theRate').text(' - Standard');
        $('#theRate').attr("val_id", '6');
        document.getElementById(uc_payCall).checked = true;
    }
    
    
    $('#theSection').text(' - ' + section);
    $('#theSection').attr("val_id", id);
	showCats();
}

function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}

function insertImage(id){
    value = 'orderimgs/' + id;
    var rte = document.getElementById('theRTEdesigner').contentWindow;
    if(rte.document.body.innerHTML.search(/<img/i) == -1 )
    {
        rte.focus();
        rte.document.execCommand("InsertImage", false, value);
    }
    else
    {
        strImage = "<img src=\""+value+"\" />";

        if ($("#theRTEdesigner")) {
            strHTML = rte.document.body.innerHTML.replace(/(<img|<IMG).*>/, strImage);
            rte.document.body.innerHTML = strHTML;
            //alert(strHTML);
        }
    }
    showHide('#cluetip');
}
function injectRTE(value) {
    var browserName=navigator.appName;
    var rte = document.getElementById('theRTEdesigner').contentWindow;
    if (browserName=="Microsoft Internet Explorer")
    {
        rte.focus();
        rte.document.selection.createRange().pasteHTML(value);
    }
    else
    {
        rte.focus();
        rte.document.execCommand("inserthtml", false, value);
    }
}

jQuery.fn.resizehandle = function() {
  return this.each(function() {
    var me = jQuery(this);
    me.after(
      jQuery('<div class="resizehandle"></div>')
      .bind('mousedown', function(e) {
        var h = me.height();
        var y = e.clientY;
        var moveHandler = function(e) {
          me
          .height(Math.max(20, e.clientY + h - y));
        };
        var upHandler = function(e) {
          jQuery('html')
          .unbind('mousemove',moveHandler)
          .unbind('mouseup',upHandler);
        };
        jQuery('html')
        .bind('mousemove', moveHandler)
        .bind('mouseup', upHandler);
      })
    );
  });
}

function getPrice(fromTab, toTab) {
    var strRTE = $('#theRTEdesigner').contents()[0].documentElement.innerHTML;

    if (strRTE.indexOf('</head>') > 0) {
        var rteSplit = strRTE.split('</head>')
    }
    else {
        var rteSplit = strRTE.split('</HEAD>');
    }
    $('#previewAd').html(rteSplit[1]).show();
    
    var startEnd = $('#rangeInline').val().toString().split(' to ');
    var startDate = $.datepicker.formatDate('mm/dd/yy', new Date(startEnd[0]));
    var endDate = $.datepicker.formatDate('mm/dd/yy', new Date(startEnd[1]));

    if ($("#theRate").text() == 'Student ') {
        $("#spEmail").html("University E-mail:");
        $("#business").hide();
        $(".department").hide();
    }
    else if ($("#theRate").text() == 'Department ') {
        $(".department").show();
        $("#spEmail").html("University E-mail:");
        $("#business").hide();
    }
    else if ($("#theRate").text() == 'Standard ') {
        $("#spEmail").html("E-mail:");
        $("#business").hide();
        $(".department").hide();
    }

    $.ajax({
        type: "POST",
        url: "pricecalc.aspx",
        data: "rte=" + rteSplit[1].replace(/&/g, 'ÿ').replace(/&nbsp;/g, ' ') + "&rate=" + $('#theRate').attr("val_id") + "&start=" + startDate + "&end=" + endDate + "&disc=" + $('#' + uc_txtDiscount).val() + "&sec=" + $('#theSection').attr("val_id") + "&from=" + fromTab + "&to=" + toTab + "&browser=" + navigator.userAgent,
        dataType: "xml",
        success: function(xml) {
            var price = $(xml).find('price').text();
            var validation = $(xml).find('val').text().replace('\n', '<br />').replace('\n', '<br />');
            var breakDown = $(xml).find('bd').text();
            var days = $(xml).find('days').text();
            var lines = $(xml).find('lines').text();
            $('#theTime').html($(xml).find('time').text());

            if (price != '$0.00') {
                $('#' + uc_lblPrice).html(price);
                $("#paymentmethod").show();
            }
            else {
                $('#' + uc_lblPrice).html('FREE');
                $("#paymentmethod").hide();
            }

            if (breakDown.length > 0) {
                $("#priceBreakDown").html('<strong>Order Breakdown:</strong><span style="font-size:14px;">' + breakDown + '</span>').show();
            }

            if (fromTab == undefined) {
                if (currentTab == "#schedule") {
                    theSwitch = function() { };
                }
            }

            if (validation.length > 0) {
                $(currentTab + " .valalert .msg").html(validation);
                $(currentTab + " .valalert").fadeIn('normal');
                if (currentTab == "#schedule") {
                    theSwitch = function() { };
                }
            }
            else {
                $(currentTab + " .valalert .msg").html(validation);
                $(currentTab + " .valalert").hide();
                $(theSwitch);
            }

            if (days > 0) {
                $("#runDays").html('Ad scheduled to run for ' + days + ' publication day(s), and will remain online for any non-publication days in between.').show();
                $(".rundays").show();
            }

            //SUBMIT ORDER
            if (fromTab == 'order' && toTab == 'order') {
                submitOrder();
            }
        }
    });
}

function pleasePreview() {
    $(currentTab + " .valalert .msg").html('Please preview your ad first.');
    $(currentTab + " .valalert").fadeIn('normal');
}

function showLivePreview() {
    showPreview = true;
    breakLoop = false;
    
    var daRTE = $('#designtable');
    var rteOffset = daRTE.offset();
    
    $('#theLivePreview').css("top", (rteOffset.top + 30) + "px").css("left", (rteOffset.left + 205) + "px");
    $('#theLivePreview .classbox').show();
    $('#theLivePreview').fadeIn('slow');
    
    $.timer(500, function(timer) {
        if (showPreview) {
            previewAd();
        }
        else {
            timer.stop();
        }
    });
}
function closeLivePreview() {
    showPreview = false;
    breakLoop = true;
    $('#theLivePreview').fadeOut('slow');
   
}

var lastRTE = '';
function previewAd() {
    var theRTE = document.getElementById('theRTEdesigner');
    var strRTE = $('#theRTEdesigner').contents()[0].documentElement.innerHTML;
    if (strRTE != lastRTE) {
        lastRTE = strRTE;
        if (strRTE.indexOf('</head>') > 0) {
            var rteSplit = strRTE.split('</head>')
        }
        else {
            var rteSplit = strRTE.split('</HEAD>');
        }
        strRTE = rteSplit[1].replace(/&nbsp;/g, ' ');

        var charCount = 0;
        var inTag = false;
        var theTag = '';

        //PARSE AD CHAR BY CHAR
        //$('#debug').val('');
        strParsed = '';
        for (i = 0; i < strRTE.length; i++) {
            if (breakLoop) {
                breakLoop = false;
                break;
            }

            var c_Char = strRTE.charAt(i);
            //$('#debug').val($('#debug').val() + c_Char);
            //CHECK FOR THE TAG
            if (c_Char == '<') {
                inTag = true;
                theTag = '';
            }
            if (inTag) {
                theTag += c_Char;
            }
            if (c_Char == '>') {
                inTag = false;
            }
            else if (!inTag) {
                if ((strRTE.charAt(i) != '\n') && (strRTE.charAt(i) != '\r')) {
                    charCount++;
                }
            }

            //TAG TESTING
            if (theTag == '<br>' || theTag == '<P>' || theTag == '<BR>') {
                theTag = '';
                charCount = 0;
            }

            if ((charCount == 20) && !inTag && strRTE.charAt(i + 1) != '<') {
                var browserName = navigator.appName;
                if (browserName == "Microsoft Internet Explorer") {
                    strParsed += c_Char + '<br />';
                }
                else {
                    strParsed += c_Char + '<br />';
                }

                $('#twentymessage').fadeIn('slow');
                
                charCount = 0;
            }
            else {
                strParsed += c_Char;
            }
        }
        breakLoop = false;
        
        $('#theLivePreview .classbox').html(strParsed);
    }
}

function submitOrder() {
    var strValid = '';
    var the_id = '';
    
    the_id = '#' + uc_txtFirstName;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> First Name is required";
    }
    else {field_val_pass(the_id);}

    the_id = '#' + uc_txtLastName;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> Last Name is required";
    }
    else { field_val_pass(the_id); }
    
    the_id = '#' + uc_txtAddress1;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> An Address is required";
    }
    else { field_val_pass(the_id); }
    
    the_id = '#' + uc_txtCity;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> City is required";
    }
    else { field_val_pass(the_id); }
    
    the_id = '#' + uc_txtState;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> State is required";
    }
    else { field_val_pass(the_id); }
    
    the_id = '#' + uc_txtZip;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> ZIP Code is required";
    }
    else { field_val_pass(the_id); }
    
    the_id = '#' + uc_txtDayPhone;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> Daytime Phone Number is required";
    }
    else { field_val_pass(the_id); }
    
    the_id = '#' + uc_txtEmail;
    if ($(the_id).val() == "") {
        field_val_fail(the_id);
        strValid += "<br /> E-mail is required";
    }
    else { field_val_pass(the_id); }

    if ($(".department").is(':visible')) {
        the_id = '#' + uc_txtDeptName;
        if ($('#' + uc_txtDeptName).val() == "") {
            strValid += "<br /> Department Name is required";
        }
        else { field_val_pass(the_id); }

        the_id = '#' + uc_txtDeptCode;
        if ($('#' + uc_txtDeptCode).val() == "") {
            strValid += "<br /> Department Code is required";
        }
        else { field_val_pass(the_id); }
    }

    if (strValid == "") {
        __doPostBack(uc_post_lbtnOrder, '');
    }
    else {
        $('#order .valalert .msg').html(strValid);
        $('#order .valalert').show();
    }
}

function field_val_fail(the_id){
    $(the_id).css('background-color', '#FFEEEB').css('border-color', '#990000');
    $('#field_' + the_id + ' span').attr('class', 'val_fail');
}

function field_val_pass(the_id){
    $(the_id).css('background-color', '#FFFFFF').css('border-color', '#CCCCCC');
    $('#field_' + the_id + ' span').attr('class', 'lbl_inp');
}