function $mcswidget(fullUrl) {
    this.fullUrl = fullUrl;
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'DrxJscriptId' + this.scriptCounter++;
}

$mcswidget.scriptCounter = 1;

$mcswidget.prototype.buildScriptTag = function() {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}

$mcswidget.prototype.removeScriptTag = function() {
    this.headLoc.removeChild(this.scriptObj);
}

$mcswidget.prototype.addScriptTag = function() {
    this.headLoc.appendChild(this.scriptObj);
}

function addScript(datasource) {
    $iframe_instance = new $mcswidget(datasource);
    $iframe_instance.buildScriptTag();
    $iframe_instance.addScriptTag();
}

$mcs_clientInfo.prototype.pageName = function() {
    var url = window.location.toString();
    var pagename;
    if (url.indexOf('?') > -1) {
        pagename = url.split('/')[url.split('/').length - 1].split('?')[0];
    }
    else {
        pagename = url.split('/')[url.split('/').length - 1];
    }
    return pagename;
}

function $mcs_clientInfo() {
    this.domain = document.domain;
    this.location = document.location;
    this.pagename = this.pageName();
}
function $mcs() {
    $info = new $mcs_clientInfo();
    this.containerID; //unique id for control
    this.cfg_aid = 'public';
    this.cfg_zip = true; //bool enable zip
    this.cfg_zipauto = true;
    this.cfg_druglist = true; //true = show drugs; false = no drugs
    this.cfg_druglimit = true; //tue = 1 drug; false = more  than 1
    this.cfg_redirect = 'PlanList'; //deep link path: PlanList, SearchDrug 
    this.cfg_initplantype = 'PDP'; //PDP, MAPD, MA, MEDIGAP
    this.cfg_subittext = 'Start';
    this.cfg_color_light = '#EFF6D4';
    this.cfg_color_medium = '#BDCA7A';
    this.cfg_color_dark = '#517617';
    this.cfg_iframe_height = '780px';
    this.cfg_iframe_width = '100%';
    this.cfg_iframe_scroll;
    this.app_path = 'http://www.drx.com/MEDICARE-PARTD/COMPARE/indivlanding.aspx';
    this.widgetstyles = new Array();
    this.cfg_enableStyles = true;
    this.cfg_enableAutoResize = true;
    this.cfg_redirectURL = '';
    this.cfg_interval = 1000;
    this.cfgid = 0;
    this.newwindow = false;
    this.cfg_polling = setInterval('$mcs.getHeight()', this.cfg_interval); ;
    //this.getHeight();

}

$mcs.prototype.getQuery = function() {
    if (window.location.toString().indexOf('ZIP=') > -1) {
        var zip = '';
        var ndc = '';
        if (window.location.toString().split('ZIP=')[1].indexOf('&') > -1) {
            zip = window.location.toString().split('ZIP=')[1].split('&')[0];
        }
        else {
            zip = window.location.toString().split('ZIP=')[1];
        }
        if (typeof window.location.toString().split('NDC=')[1] !='undefined') {
            if (window.location.toString().split('NDC=')[1].indexOf('&') > -1) {
                ndc = window.location.toString().split('NDC=')[1].split('&')[0];
            }
            else {
                ndc = window.location.toString().split('NDC=')[1];
            }
        }


        this.createIframe(zip, ndc);

    }
}

$mcs.prototype.getHeightoncomplete = function(data) {
    if (data.result != "") {
        if (document.getElementById('drx_iframe').getElementsByTagName('iframe')[0].offsetHeight - parseFloat(data.result) != 0) {
            document.getElementById('drx_iframe').getElementsByTagName('iframe')[0].style.height = data.result + 'px';

        }
    }
}

$mcs.prototype.getHeight = function() {
    if (document.getElementById('drx_iframe') != null && document.getElementById('drx_iframe').getElementsByTagName('iframe')[0] != null) {
        if (this.cfg_enableAutoResize) {
            addScript('http://www.drx.com/MEDICARE-PARTD/COMPARE/widget/handler.ashx?getheight=0');
        }
    }
}

//    this.selectedNDC = '';
$mcs.prototype.selectedNDC = '';

$mcs.prototype.generateCSS = function() {
    this.widgetstyles.push('text-align:left;');                                     //0
    this.widgetstyles.push('font-size:12px;');                                      //1
    this.widgetstyles.push('font-family:arial;');                                   //2
    this.widgetstyles.push('border:1px ' + this.cfg_color_medium + ' solid;');      //3
    this.widgetstyles.push('padding:5px;');                                         //4
    this.widgetstyles.push('width:60px;');                                          //5
    this.widgetstyles.push('position:absolute;');                                   //6
    this.widgetstyles.push('background-color:' + this.cfg_color_light + ';');       //7
    this.widgetstyles.push('background-color:' + this.cfg_color_medium + ';');      //8
    this.widgetstyles.push('text-decoration:none;');                                //9
    this.widgetstyles.push('color:' + this.cfg_color_dark + ';');                   //10
    this.widgetstyles.push('display:block;');                                       //11
    this.widgetstyles.push('padding:2px 5px;');                                     //12
    this.widgetstyles.push('border:1px ' + this.cfg_color_dark + ' solid;');        //13
    this.widgetstyles.push('color:#ff0000;');                                       //14
    this.widgetstyles.push('font-size:.9em;');                                      //15
    this.widgetstyles.push('width:100%;');                                          //16
}

$mcs.prototype.buildWidget = function() {
    if (window.location.toString().indexOf('ZIP=') == -1) {
        this.generateCSS();
        var sb = new Array();
        sb.push('<div id=\"' + this.containerID + '\" style=\"width:' + this.cfg_iframe_width + '\">loading...</div>')
        document.write(sb.join(''));

        var container = document.getElementById(this.containerID);

        container.innerHTML = '';
        sb.length = 0;
        if (!this.cfg_enableStyles) {
            this.widgetstyles.length = 0;
        }

        //enable autocomplete event
        var autcompleteevent = 'void(0)';
        if (this.cfg_zipauto) {
            autcompleteevent = '$mcs.getZipcodes(event, this)';
        }
        //enables zip field
        sb.push('<table style=\"' + this.widgetstyles[16] + this.widgetstyles[1] + this.widgetstyles[2] + this.widgetstyles[3] + this.widgetstyles[7] + '\"><tbody>');
        sb.push('<thead><tr><th style=\"' + this.widgetstyles[0] + this.widgetstyles[4] + '\">ZIP Code * <span id=\"mcs_zipvalidation\" style=\"' + this.widgetstyles[14] + this.widgetstyles[15] + '\"></span></th>')
        if (this.cfg_druglist) {
            sb.push('<th style=\"' + this.widgetstyles[0] + this.widgetstyles[4] + '\">Drug</th>');
        }
        sb.push('</tr></thead>');
        sb.push('<tr>');
        if (this.cfg_zip) {

            sb.push('<td><div style=\"' + this.widgetstyles[4] + '\"><input style=\"' + this.widgetstyles[5] + '\" autocomplete=\"off\" type=\"text\" id=\"mcs_zipinput\" maxlength=\"5\" onkeydown=\"$mcs.zip_validation(event, this.value, false)\" onkeyup=\"' + autcompleteevent + '\"/>');
            sb.push('<input type=\"button\" id=\"mcs_zipsubmit\" onclick=\"$mcs.zip_validation(null, document.getElementById(\'mcs_zipinput\').value, true)\" value=\"' + this.cfg_subittext + '\"/>');
            sb.push('</div></td>');
        }

        if (this.cfg_druglist) {
            sb.push('<td><div style=\"' + this.widgetstyles[4] + '\" id=\"mcs_drugList\"></div></td>');
            addScript('http://www.drx.com/MEDICARE-PARTD/COMPARE/widget/handler.ashx?getDrugList=1&returnMethod=$mcs.GetDrugListoncomplete');
        }

        sb.push('</tr>');
        if (this.cfg_zipauto) {
            sb.push('<tr><td colspan=\"2\"><div style=\"' + this.widgetstyles[6] + this.widgetstyles[8] + '\" id=\"autocomplete_ui\"></div></td></tr>');
        }
        sb.push('</tbody></table>');
        sb.push('<div id=\"drx_iframe\"></div>');
        container.innerHTML = sb.join('');
    }
    else {
        this.getQuery();
    }
}

$mcs.prototype.autocomplete_clear = function() {
  if (document.getElementById('autocomplete_ui'))
    document.getElementById('autocomplete_ui').innerHTML = '';
}

$mcs.prototype.zip_validation = function(e, value, isbutton) {
    if (document.getElementById('autocomplete_ui')) {
        document.getElementById('autocomplete_ui').style.display = '';
    }
    var validreg = /^\d{5}$/
    if (isbutton) {
        if (value.length == 5 && value.search(validreg) != -1) {
            this.zipSubmit();
        }
        else
            document.getElementById('mcs_zipvalidation').innerHTML = 'Invalid ZIP code';
    }
    else {
        if (e.keyCode == 13) {
            if (value.length == 5 && value.search(validreg) != -1) {
                this.zipSubmit();
            }
            else {
                document.getElementById('mcs_zipvalidation').innerHTML = 'Invalid ZIP code';
            }
            return false;
        }
        else {
            document.getElementById('mcs_zipvalidation').innerHTML = '';
        }
    }
}


$mcs.prototype.getZipcodes = function(e, obj) {
    if (e.keyCode != 13) {
        if (obj.value.length == 0) {
            this.autocomplete_clear();
        }
        addScript('http://www.drx.com/MEDICARE-PARTD/COMPARE/widget/handler.ashx?ZIP=' + obj.value + '&returnMethod=$mcs.getZipcodesOncomplete');
    }
}

$mcs.prototype.zipSubmit = function() {
        var path = this.app_path + '?AID=' + this.cfg_aid + '&ZIP=' + document.getElementById('mcs_zipinput').value + '&page=' + this.cfg_redirect + '&NDC=' + this.selectedNDC + '&planType=' + this.cfg_initplantype;
        this.launch(path, true);
}

$mcs.prototype.updateNDC = function(id) {
    
    this.selectedNDC = id;
}

$mcs.prototype.GetDrugListoncomplete = function(data) {
    var sb = new Array();
    sb.push('<select id=\"mcs_selecteddrug\" onchange=\"$mcs.updateNDC(this.value)\">');
    sb.push('<option value=\"\">Select a drug</option>');
    for (var d = 0; d < data.result.length; d++) {
        sb.push('<option value=\"' + data.result[d].ndc + '\">' + data.result[d].name + '</option>');
    }
    sb.push('</select>');
    document.getElementById('mcs_drugList').innerHTML = sb.join('');
}

$mcs.prototype.createIframe = function(zip, ndc) {
    var sb = new Array();
    sb.push('<div id=\"drx_iframe\" style=\"width:' + this.cfg_iframe_width + '\"></div>')
    document.write(sb.join(''));

    sb.length = 0;

    if (this.cfg_enableAutoResize) {
        sb.push('<iframe scrolling=\"no\" frameborder=\"0\" width=\"' + this.cfg_iframe_width + '\"></iframe>');
    }
    else {
        sb.push('<iframe scrolling=\"auto\" frameborder=\"0\" width=\"' + this.cfg_iframe_width + '\" height=\"' + this.cfg_iframe_height + '\"></iframe>');
    }
    document.getElementById('drx_iframe').innerHTML = sb.join('');
    document.getElementById('drx_iframe').getElementsByTagName('iframe')[0].src = this.app_path + '?AID=' + this.cfg_aid + '&ZIP=' + zip + '&page=' + this.cfg_redirect + '&NDC=' + ndc + '&planType=' + this.cfg_initplantype;

}

$mcs.prototype.redirection = '';


$mcs.prototype.launch = function(url, redirect) {
    if (document.getElementById('autocomplete_ui'))
        document.getElementById('autocomplete_ui').style.display = 'none';
    if (this.cfg_redirectURL.length == 0) {
        document.getElementById('drx_iframe').innerHTML = '';
        var sb = new Array();
        if (this.cfg_enableAutoResize) {
            sb.push('<iframe scrolling=\"no\" frameborder=\"0\" width=\"' + this.cfg_iframe_width + '\"></iframe>');
        }
        else {
            sb.push('<iframe scrolling=\"auto\" frameborder=\"0\" width=\"' + this.cfg_iframe_width + '\" height=\"' + this.cfg_iframe_height + '\"></iframe>');
        }
        document.getElementById('drx_iframe').innerHTML = sb.join('');
        document.getElementById('drx_iframe').getElementsByTagName('iframe')[0].src = url;
        this.autocomplete_clear();

    }
    else {
        var ndcparamvalue = '';
        if (document.getElementById('mcs_selecteddrug')) {
            ndcparamvalue = '&NDC=' + document.getElementById('mcs_selecteddrug').value;
        }
        this.redirection = 'https://partners.destinationrx.com/aw.aspx?B=7&A=' + this.cfgid + '&Task=Click&TargetURL=' + escape(this.cfg_redirectURL) + escape('?ZIP=' + document.getElementById('mcs_zipinput').value + ndcparamvalue);
        if (redirect && !this.newwindow) {
            document.location = this.redirection;
        }
        else if (redirect && this.newwindow) {
            window.open(this.redirection);
        }

    }
}

$mcs.prototype.getZipcodesOncomplete = function(data) {
    if (data.result.length > 0) {
        var sb = new Array();
        sb.push('<table id=\"autocomplete_zip\" style=\"' + this.widgetstyles[13] + '\">');
        var getDrug = '';

        for (var d = 0; d < data.result.length; d++) {
            sb.push('<tr><td><a onmouseout=\"this.style.backgroundColor=\'transparent\'\" onmouseover=\"this.style.backgroundColor=\'#ffffff\'\" style=\"' + this.widgetstyles[9] + this.widgetstyles[10] + this.widgetstyles[11] + this.widgetstyles[12] + '\" href=\"javascript:void(0)\" title=\"' + data.result[d].county + '\"  onclick=\"document.getElementById(\'mcs_zipinput\').value = \'' + data.result[d].zip + '\';$mcs.launch(\'' + this.app_path + '?AID=' + this.cfg_aid + '&ZIP=' + data.result[d].zip + '&page=' + this.cfg_redirect + '&NDC=' + this.selectedNDC + '&planType=' + this.cfg_initplantype + '\')\">' + data.result[d].zip + ' - ' + data.result[d].county + '</a></td></tr>');
        }
        sb.push('</table>');
        if (document.getElementById('autocomplete_ui'))
           document.getElementById('autocomplete_ui').innerHTML = sb.join('');
    }
    else {
        document.getElementById('mcs_zipvalidation').innerHTML = 'Invalid ZIP code';
        this.autocomplete_clear();
    }
}

function init() {
    $mcs = new $mcs();
}
