(function($) {
    var oldDiv = "";
    $.fn.dd = function(options) {
        $this =  this;
        options = $.extend({
            height:120,
            visibleRows:7,
            rowHeight:38,
            showIcon:true,
            zIndex:9999,
            style:''
        }, options);
        var selectedValue = "";
        var totalWidth = 0;
        insideWindow = true;
        config = {postElementHolder:'_msddHolder', postID:'_msdd', postTitleID:'_title',postTitleTextID:'_titletext',postChildID:'_child',postAID:'_msa',postOPTAID:'_msopta',postInputID:'_msinput', postArrowID:'_arrow', postInputhidden:'_inp'};
        styles = {dd:'dd', ddTitle:'ui-button ui-state-default ui-corner-all', arrow:'arrow', ddChild:'ddChild', disbaled:.30};
        attributes = {actions:"onfocus,onblur,onchange,onclick,ondblclick,onmousedown,onmouseup,onmouseover,onmousemove,onmouseout,onkeypress,onkeydown,onkeyup", prop:"size,multiple,disabled,tabindex"};
        var elementid = $(this).attr("id");
        var inlineCSS = $(this).attr("style");
        options.style += (inlineCSS==undefined) ? "" : inlineCSS;
        var allOptions = $(this).children();
        var a_array = {};//stores id and html, value
        //var selection = {};
        //create wrapper
        createDropDown();
    
    function getPostID(id) {
        return elementid+config[id];
    };
    function getOptionsProperties(option) {
        //returns : options, selected, icons
        var currentOption = option;
        var styles = $(currentOption).attr("style");
        return styles;
    };
    function createATags() {
        var childnodes = allOptions;
        var aTag = "";
        var aidfix = getPostID("postAID");
        var aidoptfix = getPostID("postOPTAID");
        var selectedndex= document.getElementById(elementid).selectedIndex;
        childnodes.each(function(current){
                                 var currentOption = childnodes[current];
                                 //OPTGROUP
                                 if(currentOption.nodeName == "OPTGROUP") {
                                      aTag += "<div class='opta'>";
                                     aTag += "<span style='font-weight:bold;font-style:italic; clear:both;'>"+$(currentOption).attr("label")+"</span>";
                                     var optChild = $(currentOption).children();
                                     optChild.each(function(currentopt){
                                                            var currentOptOption = optChild[currentopt];
                                                             var aid = aidoptfix+"_"+(current)+"_"+(currentopt);
                                                             var arrow = $(currentOptOption).attr("title");
                                                             arrow = (arrow.length==0) ? "" : '<img src="'+arrow+'" align="left" /> ';
                                                             var sText = $(currentOptOption).text();
                                                             
                                                             var iWidth =  (sText.length*8)+10;       //  alert(iWidth);
                                                             if (totalWidth < iWidth) totalWidth = iWidth;     alert(totalWidth); 
                                                             
                                                             var sValue = $(currentOptOption).val();
                                                             var sEnabledClass = ($(currentOptOption).attr("disabled")==true) ? "disabled" : "enabled";
                                                             a_array[aid] = {html:arrow + sText, value:sValue, text:sText};
                                                             var innerStyle = getOptionsProperties(currentOptOption);
                                                             if(selectedndex == currentopt) {
                                                                 aTag += '<a href="javascript:void(0);" class="selected '+sEnabledClass+'"';
                                                             } else {
                                                                 aTag += '<a  href="javascript:void(0);" class="'+sEnabledClass+'"';
                                                             };
                                                             if(innerStyle!=false)
                                                             aTag +=  ' style="'+innerStyle+'"';
                                                             aTag +=  ' id="'+aid+'">';
                                                             aTag += arrow + sText+'</a>';                                                             
                                                            });
                                     aTag += "</div>";
                                     
                                 } else {
                                     var aid = aidfix+"_"+(current);
                                     var arrow = $(currentOption).attr("title");
                                     arrow = (arrow.length==0) ? "" : '<img src="'+arrow+'" align="left" /> ';                                     
                                     var sText = $(currentOption).text();
                                     
                                     var iWidth =  (sText.length*8)+10;       //  alert(iWidth);
                                     if (totalWidth < iWidth) totalWidth = iWidth;  //   alert(totalWidth); 
                                     
                                     var sValue = $(currentOption).val();
                                     var sEnabledClass = ($(currentOption).attr("disabled")==true) ? "disabled" : "enabled";
                                     a_array[aid] = {html:arrow + sText, value:sValue, text:sText};
                                     var innerStyle = getOptionsProperties(currentOption);
                                     if(selectedndex == current) {
                                         aTag += '<a href="javascript:void(0);" class="selected '+sEnabledClass+'"';
                                     } else {
                                        aTag += '<a  href="javascript:void(0);" class="'+sEnabledClass+'"';
                                     };
                                     if(innerStyle!=false)
                                     aTag +=  ' style="'+innerStyle+'"';
                                     aTag +=  ' id="'+aid+'">';
                                     aTag += arrow + sText+'</a>';                                                             
                                 };
                                 });
        return aTag;
    };
    function createTitleDiv() {
        var titleid = getPostID("postTitleID");
        var arrowid = getPostID("postArrowID");
        var titletextid = getPostID("postTitleTextID");
        var inputhidden = getPostID("postInputhidden");
        var sText = $("#"+elementid+" option:selected").text();
        var arrow = $("#"+elementid+" option:selected").attr("title");
        arrow = (arrow.length==0 || arrow==undefined || options.showIcon==false) ? "" : '<img src="'+arrow+'" align="left" /> ';
        var sDiv = '<div id="'+titleid+'" class="'+styles.ddTitle+'"';
        sDiv += '>';
        sDiv += '<span id="'+arrowid+'" class="'+styles.arrow+'"></span><span class="textTitle" id="'+titletextid+'">'+arrow + sText+'&nbsp;<img src="/css/downarrow.gif"/></span></div>';
        return sDiv;
    };
    function createDropDown() {
        var changeInsertionPoint = false;
        var id = getPostID("postID");
        var titleid = getPostID("postTitleID");
        var titletextid = getPostID("postTitleTextID");
        var childid = getPostID("postChildID");
        var arrowid = getPostID("postArrowID");
        var iWidth2 = $("#"+elementid).width()+150;
        
        var sText = $("#"+elementid+" option:selected").text();
        var iWidth =  (sText.length*8);       //  alert(iWidth);
        
        if (totalWidth < iWidth) totalWidth = iWidth;
        
        var sStyle = options.style;
        if($("#"+id).length>0) {
            $("#"+id).remove();
            changeInsertionPoint = true;
        }
        var sDiv = '<div id="'+id+'" class="'+styles.dd+'"';
        sDiv += (sStyle!="") ? ' style="'+sStyle+'"' : '';
        sDiv += '>';
        //create title bar
        sDiv += createTitleDiv();
        //create child
        sDiv += '<div id="'+childid+'" class="'+styles.ddChild+'"';
        sDiv += (sStyle!="") ? ' style="'+sStyle+'"' : ''; 
        sDiv += '>';
        sDiv += createATags();
        sDiv += "</div>";
        sDiv += "</div>";
        if(changeInsertionPoint==true) {
            var sid =getPostID("postElementHolder");
            $("#"+sid).after(sDiv);
        } else {
            $("#"+elementid).after(sDiv);
        }
        $("#"+id).css("width", totalWidth+"px");
        $("#"+childid).css("width", (totalWidth-2)+"px");
        if(allOptions.length>options.visibleRows) {
            var margin = parseInt($("#"+childid+" a:first").css("padding-bottom")) + parseInt($("#"+childid+" a:first").css("padding-top"));
            var iHeight = ((options.rowHeight)*options.visibleRows) - margin;
            $("#"+childid).css("height", iHeight+"px");
        }
        //set out of vision
        if(changeInsertionPoint==false) {
            setOutOfVision();
            addNewEvents(elementid);
        }
        if($("#"+elementid).attr("disabled")==true) {
            $("#"+id).css("opacity", styles.disbaled);
        } else {
            applyEvents();
            //add events
            //arrow hightlight
            $("#"+titleid).bind("mouseover", function(event) {
                                                      hightlightArrow(1);
                                                      });
            $("#"+titleid).bind("mouseout", function(event) {
                                                      hightlightArrow(0);
                                                      });
            //open close events
            $("#"+childid+ " a.enabled").bind("click", function(event) {
                                                         $("#"+childid).unbind("mouseover");
                                                         setInsideWindow(false);
                                                         $("#"+childid+ " a.selected").removeClass("selected");
                                                         $(this).addClass("selected");
                                                         var sText = (options.showIcon==false) ? $(this).text() : $(this).html();
                                                         setTitleText(sText);
                                                         setValue();
                                                         closeMe();
                                                         });
            $("#"+childid+ " a.disabled").css("opacity", styles.disbaled);
            $("#"+childid).bind("mouseout", function(event) {setInsideWindow(false);});
            
            $("#"+titleid).bind("click", function(event) {
                                                  setInsideWindow(false);
                                                    if($("#"+childid+":visible").length==1) {
                                                        $("#"+childid).unbind("mouseover");
                                                        //closeMe();
                                                    } else {
                                                        $("#"+childid).bind("mouseover", function(event) {setInsideWindow(true);});
                                                        openMe();
                                                    };
                                                      });
            $("#"+titleid).bind("mouseout", function(evt) {
                                                     setInsideWindow(false);
                                                     })
        };
    };
    function addNewEvents(id) {
        document.getElementById(id).refresh = function(e) {
            $("#"+this.id).dd(options);
        };
    };
    function setInsideWindow(val) {
        insideWindow = val;
    };
    function getInsideWindow() {
        return insideWindow;
    };
    function applyEvents() {
        var mainid = getPostID("postID");
        var actions_array = attributes.actions.split(",");
        for(var iCount=0;iCount<actions_array.length;iCount++) {
            var action = actions_array[iCount];
            var actionFound = $("#"+elementid).attr(action);
            //alert(actionFound);
            if(actionFound!=undefined) {
                switch(action) {
                    case "onfocus": 
                    $("#"+mainid).bind("mouseenter", function(event) {
                                                       document.getElementById(elementid).focus();
                                                       });
                    break;
                    case "onclick": 
                    $("#"+mainid).bind("click", function(event) {
                                                       document.getElementById(elementid).onclick();
                                                       });
                    break;
                    case "ondblclick": 
                    $("#"+mainid).bind("dblclick", function(event) {
                                                       document.getElementById(elementid).ondblclick();
                                                       });
                    break;
                    case "onmousedown": 
                    $("#"+mainid).bind("mousedown", function(event) {
                                                       document.getElementById(elementid).onmousedown();
                                                       });
                    break;
                    case "onmouseup": 
                    //has in closeMe mthod
                    $("#"+mainid).bind("mouseup", function(event) {
                                                       document.getElementById(elementid).onmouseup();
                                                       //setValue();
                                                       });
                    break;
                    case "onmouseover": 
                    $("#"+mainid).bind("mouseover", function(event) {
                                                       document.getElementById(elementid).onmouseover();
                                                       });
                    break;
                    case "onmousemove": 
                    $("#"+mainid).bind("mousemove", function(event) {
                                                       document.getElementById(elementid).onmousemove();
                                                       });
                    break;
                    case "onmouseout": 
                    $("#"+mainid).bind("mouseout", function(event) {
                                                       document.getElementById(elementid).onmouseout();
                                                       });
                    break;
                };
            };
        };
        
    };
    function setOutOfVision() {
        var sId = getPostID("postElementHolder");
        $("#"+elementid).after("<div style='height:0px; overflow:hidden;position:absolute' id='"+sId+"'></div>");
        $("#"+elementid).appendTo($("#"+sId));
    };
    function setTitleText(sText) {
        var titletextid = getPostID("postTitleTextID");
        $("#"+titletextid).html(sText);
    };
    function next() {
        var titletextid = getPostID("postTitleTextID");
        var childid = getPostID("postChildID");
        var allAs = $("#"+childid + " a.enabled");
        for(var current=0;current<allAs.length;current++) {
            var currentA = allAs[current];
            var id = $(currentA).attr("id");
            if($(currentA).hasClass("selected") && current<allAs.length-1) {
                $("#"+childid + " a.selected").removeClass("selected");
                $(allAs[current+1]).addClass("selected");
                var selectedA = $("#"+childid + " a.selected").attr("id");
                var sText = (options.showIcon==false) ? a_array[selectedA].text : a_array[selectedA].html;
                setTitleText(sText);
                if(parseInt(($("#"+selectedA).position().top+$("#"+selectedA).height()))>=parseInt($("#"+childid).height())) {
                    $("#"+childid).scrollTop(($("#"+childid).scrollTop())+$("#"+selectedA).height()+$("#"+selectedA).height());
                };
                break;
            };
        };
    };
    function previous() {
        var titletextid = getPostID("postTitleTextID");
        var childid = getPostID("postChildID");
        var allAs = $("#"+childid + " a.enabled");
        for(var current=0;current<allAs.length;current++) {
            var currentA = allAs[current];
            var id = $(currentA).attr("id");
            if($(currentA).hasClass("selected") && current!=0) {
                $("#"+childid + " a.selected").removeClass("selected");
                $(allAs[current-1]).addClass("selected");
                var selectedA = $("#"+childid + " a.selected").attr("id");
                var sText = (options.showIcon==false) ? a_array[selectedA].text : a_array[selectedA].html;
                setTitleText(sText);
                if(parseInt(($("#"+selectedA).position().top+$("#"+selectedA).height())) <=0) {
                    $("#"+childid).scrollTop(($("#"+childid).scrollTop()-$("#"+childid).height())-$("#"+selectedA).height());
                };
                break;
            };
        };
    };
    function setValue() {
        var childid = getPostID("postChildID");
        var sText = $("#"+childid + " a.selected").text();
        var selectedA = $("#"+childid + " a.selected").attr("id");
        var sValue = a_array[selectedA].value;
        $("#"+elementid + " option:selected").text($.trim(sText));
        $("#"+elementid + " option:selected").val(sValue);
    };
    function openMe() {
        var childid = getPostID("postChildID");
        if(oldDiv!="" && childid!=oldDiv) { 
            $("#"+oldDiv).slideUp("fast");
            $("#"+oldDiv).css({zIndex:'0'});
        }
        if($("#"+childid).css("display")=="none") {
            selectedValue = a_array[$("#"+childid +" a.selected").attr("id")].text;
            $(document).bind("keydown", function(event) {
                                                    var keyCode = event.keyCode;                                            
                                                    if(keyCode==39 || keyCode==40) {
                                                        //move to next
                                                        event.preventDefault(); event.stopPropagation();
                                                        next();
                                                    };
                                                    if(keyCode==37 || keyCode==38) {
                                                        event.preventDefault(); event.stopPropagation();
                                                        //move to previous
                                                        previous();
                                                    };
                                                    if(keyCode==27 || keyCode==13) {
                                                        closeMe();
                                                        setValue();
                                                    };
                                                    if($("#"+elementid).attr("onkeydown")!=undefined) {
                                                            document.getElementById(elementid).onkeydown();
                                                        };                                                        
                                                       });
            $(document).bind("keyup", function(event) {
                                                    if($("#"+elementid).attr("onkeyup")!=undefined) {
                                                        //$("#"+elementid).keyup();
                                                        document.getElementById(elementid).onkeyup();
                                                    };                                                 
                                                 });

                    $(document).bind("mouseup", function(evt){
                                                            if(getInsideWindow()==false) {
                                                             closeMe();
                                                            }
                                                         });                                                      
            $("#"+childid).css({zIndex:options.zIndex});
            $("#"+childid).slideDown("fast");
        if(childid!=oldDiv) {
            oldDiv = childid;
        }
        };
    };
    function closeMe() {
                var childid = getPostID("postChildID");
                $(document).unbind("keydown");
                $(document).unbind("keyup");
                $(document).unbind("mouseup");
                $("#"+childid).slideUp("fast", function(event) {
                                                            checkMethodAndApply();
                                                            $("#"+childid).css({zIndex:'0'});
                                                            });
        
    };
    function checkMethodAndApply() {
        var childid = getPostID("postChildID");
        if($("#"+elementid).attr("onchange")!=undefined) {
            var currentSelectedValue = a_array[$("#"+childid +" a.selected").attr("id")].text;
            if(selectedValue!=currentSelectedValue){document.getElementById(elementid).onchange();};
        }
        if($("#"+elementid).attr("onmouseup")!=undefined) {
            document.getElementById(elementid).onmouseup();
        }
        if($("#"+elementid).attr("onblur")!=undefined) { 
            $(document).bind("mouseup", function(evt) {
                                                   $("#"+elementid).focus();
                                                   $("#"+elementid)[0].blur();
                                                   setValue();
                                                   $(document).unbind("mouseup");
                                                });
        };
    };
    function hightlightArrow(ison) {
        var arrowid = getPostID("postArrowID");
        if(ison==1)
            $("#"+arrowid).css({backgroundPosition:'0 100%'});
        else 
            $("#"+arrowid).css({backgroundPosition:'0 0'});
    };
    };
    $.fn.msDropDown = function(properties) {
        var dds = $(this);
        for(var iCount=0;iCount<dds.length;iCount++) {
            var id = $(dds[iCount]).attr("id");
            if(properties==undefined) {
                $("#"+id).dd();
            } else {
                $("#"+id).dd(properties);
            };
        };        
    };
})(jQuery);

// ##################################################################################################################
//
//                                  Dialog
//
// ##################################################################################################################
$(function() {        
  var id = $("#profileid"), name = $("#newProfileName"),  url = $("#newProfileURL"),  desc = $("#newProfileDesc"),  
    allFields = $([]).add(name).add(url).add(desc),  tips = $("#validateTips");
  
    
  function updateTips(t) { tips.text(t).effect("highlight",{},1500);}
  function checkLength(o,n,min,max) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass("ui-state-error");
                updateTips("Length of " + n + " must be between "+min+" and "+max+".");
                return false;
            } else {
                return true;
            }

        }
  function checkRegexp(o,regexp,n) {

            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass("ui-state-error");
                updateTips(n);
                return false;
            } else {
                return true;
            }

        }
        
  $("#dialog").dialog({ bgiframe: true, autoOpen: false, height: 400, width: 460, modal: true,
    buttons: {
        Cancel: function() { $(this).dialog("close");},
        "Save": function() {
            var bValid = true;  allFields.removeClass("ui-state-error");

            bValid = bValid && checkLength(name,"Name",3,25);
            bValid = bValid && checkLength(url,"URL",6,80);
            bValid = bValid && checkLength(desc,"Describtion",0,255);
            if (bValid) {
                $.post("lp.php", { addProfile: "go", url: url.val(), name:  name.val(), desc: desc.val(), id: id.val() },
                function(data){ returned = data.split("|+|");  $("#result").html(returned[0]);  $("#ajax-load").toggle(); }, "html");
                // $('#users tbody').append('<tr>' + '<td>' + name.val() + '</td>' +  '<td>' + url.val() + '</td>' +  '<td>' + desc.val() + '</td>' + '</tr>'); 
                $(this).dialog('close');
            }
        }                
    },
    close: function() { allFields.val("").removeClass("ui-state-error"); }
  });        
        
  $('#edit-user').click(function() { 
    var id = ($('#profiles').val());
   
    $.post("lp.php", { getProfileInfo: id },
      function(data){ returned = data.split("|+|");  $("#res").html();  
        $('#newProfileName').val(returned[3]);  $('#newProfileURL').val(returned[5]); $('#newProfileDesc').val(returned[4]);  $('#profileid').val(id);
      }, "html");
      
    $('#dialog').dialog('open');   
      
  })
        
  .hover( function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); })
  .mousedown(function(){$(this).addClass("ui-state-active"); })
  .mouseup(function(){ $(this).removeClass("ui-state-active");});
        
  $('#create-user').click(function() { $('#profileid').val(""); $('#dialog').dialog('open');})
          
  .hover( function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); })
  .mousedown(function(){$(this).addClass("ui-state-active"); })
  .mouseup(function(){ $(this).removeClass("ui-state-active");});  
  
});

function showValue(prID){
    $.post("lp.php", { SetCurrProfile: prID }, function(data){ window.location = "merchants.html";}, "html"); 
}



function addProfile(){
 $('#profileid').val(''); $('#dialog').dialog('open');
}
function editProfile(){
  var id = ($('#profiles').val());
   
    $.post("lp.php", { getProfileInfo: id },
      function(data){ returned = data.split("|+|");  $("#res").html();  
        $('#newProfileName').val(returned[3]);  $('#newProfileURL').val(returned[5]); $('#newProfileDesc').val(returned[4]);  $('#profileid').val(id);
        $('#dialog').dialog('open');   
      }, "html");
      
    
}

/////////
$(function() {

$("#progrdlg").dialog({ bgiframe: true, autoOpen: false, height: 400, width: 600, modal: true });
});
