locator_border_width = 4;
locator_size = 100;
locator_inner_border_width = 2;

tag_name_border_width = 1;
img_border_offset = 0;
user_img_width=17;
user_img_height=17;


var last_tag_show = 1;
var tags=new Array();
var userfriend="";
function getLocator() {
    var locator = $('locator');
    if (!locator) {
        locator = E('DIV');
        locator.id = 'locator';
        locator.style.display = 'none';

        locator.style.width = locator_size + "px";
        locator.style.height = locator_size + "px";
        locator.style.border = locator_border_width + "px solid black";
        locator.style.position = 'absolute';

        // put the locator inside the picture
        var thePhoto = $('thePhoto');
        locator.style.left = findPosX(thePhoto) + 'px';
        locator.style.top = findPosY(thePhoto) + 'px';

        var innerLocator = E('DIV');
        innerLocator.id = 'inner_locator';
        innerLocator.style.border = locator_inner_border_width + "px solid #ccc";
        innerLocator.style.width = (locator_size - 2*locator_inner_border_width) + "px";
        innerLocator.style.height = (locator_size - 2*locator_inner_border_width) + "px";

        locator.appendChild(innerLocator);

        document.body.appendChild(locator);
    }
    locator.style.display = 'none';
    return locator;
}

function getSelector(fX, fY) {
    var selector = $('selector');
    if (!selector) {
        selector = E('DIV');
        selector.id = 'selector';
        selector.style.display = 'none';
        selector.style.position = 'absolute';
        
        selector.style.border = "1px solid #ccc";

        // put the selector inside the picture
        var thePhoto = $('thePhoto');
        selector.style.left = findPosX(thePhoto) + 'px';
        selector.style.top = findPosY(thePhoto) + 'px';

        var form = E('FORM');
        form.id = 'selector_form';
        form.onsubmit = function() {return false;};
        form.appendChild(createFormInput('hidden', '_submit_check', 'create_tag'));
        form.appendChild(createFormInput('hidden', 'entitymedia_id', entitymedia_id));
        form.appendChild(createFormInput('hidden', 'fX'));
        form.appendChild(createFormInput('hidden', 'fY'));
                                          
        var querybox = E('DIV');
        querybox.style.padding = "5px";
        querybox.style.backgroundColor = "white";
        querybox.innerHTML = "<b>填写标签:</b><br/><INPUT class='text_field' autocomplete='off' id='selector_input_text' name='tag' onkeyup='selectorSearch(this, event);' type='text'/><br/><b>或选择用户:</b>";
        form.appendChild(querybox);

        var results = E('DIV');
        results.id = 'selector_results';
        results.tabIndex = -1;
        results.style.padding = "5px";
        results.style.backgroundColor = "#eee";
        results.style.borderTop = "1px solid #aaa";
        results.style.borderBottom = "1px solid #aaa";
        results.style.height = "125px";
        results.style.width = "148px";
        results.style.overflow = 'auto';
        form.appendChild(results);

        var buttons = E('DIV');
        buttons.style.padding = "5px";
        buttons.style.backgroundColor = "white";
        buttons.innerHTML = "<CENTER><INPUT type='button' value='标记' onclick='submitTag()' /> <INPUT type='button' value='取消' onclick='hideTagging();'/></CENTER>";
        form.appendChild(buttons);
        selector.appendChild(form);

        document.body.appendChild(selector);
    }
    selector.style.display = 'none';

    var form = $('selector_form');
    var fxField = getFormField(form, 'fX');
    fxField.value = fX;
    var fYField = getFormField(form, 'fY');
    fYField.value = fY;

    return selector;
}

function getTagName() {
    var tagName = $('tag_name');
    if (!tagName) {
        tagName = E('DIV');
        tagName.id = 'tag_name';
        tagName.style.display = 'none';
        tagName.style.position = 'absolute';
        tagName.style.border = tag_name_border_width + "px solid #ccc";
        tagName.style.width = (locator_size - 2*locator_inner_border_width) + 'px';
        tagName.style.cursor = "pointer";

        // put the tagName inside the picture
        var thePhoto = $('thePhoto');
        tagName.style.left = findPosX(thePhoto) + 'px';
        tagName.style.top = findPosY(thePhoto) + 'px';

        var tagTopSpacer = E('DIV');
        tagTopSpacer.style.width = tagName.style.width;
        tagTopSpacer.innerHTML = "<img src='/images/photoTag/clear.gif' height='" + (locator_size - 2*locator_inner_border_width) + "' width='" + (locator_size - 2*locator_inner_border_width) + "'/>";

        tagName.appendChild(tagTopSpacer);

        var tagInfo = E('DIV');
        tagInfo.id = "tag_info";
        tagInfo.style.backgroundColor = "white";
        tagInfo.style.padding = "3px";
        tagInfo.style.width = (locator_size - 2*locator_inner_border_width - 6) + 'px';

        tagInfo.innerHTML = "";

        tagName.appendChild(tagInfo);

        document.body.appendChild(tagName);
    }
    tagName.style.display = 'none';
    return tagName;
}

function enableTagging(readonly, is_on_page_load) {
    if (is_on_page_load && $('locator')) return;

    // call to unset all values
    disableTagging();

    var locator = getLocator();
    hideLocator();

    var thePhoto = $('thePhoto');
    if (!readonly) {
        thePhoto.onclick = function(event) {
            diffX = findMouseX(event) - findPosX(thePhoto);
            diffY = findMouseY(event) - findPosY(thePhoto);
            
            showLocator(diffX/thePhoto.width, diffY/thePhoto.height, true);
            showSelector(diffX/thePhoto.width, diffY/thePhoto.height, locator.offsetLeft, locator.offsetTop);
            hideTagName();
            return false;
        };

        thePhoto.style.cursor = 'crosshair';
        locator.onclick = thePhoto.onclick;
        locator.style.cursor = 'crosshair';//heshiliang

        thePhoto.onmouseover = function() {
            hideTagName();
        };
    }

    thePhoto.onmousemove = function(event) {
        findShowTagName(event);
    };
    
    thePhoto.onmouseout = function(event) {
        // we only really leave if we are outside the photo
        mouseX = findMouseX(event);
        mouseY = findMouseY(event);
        
        photoX = findPosX(thePhoto) + img_border_offset;
        photoY = findPosY(thePhoto) + img_border_offset;
        
        if (mouseX < photoX || mouseX >= photoX+thePhoto.width ||
            mouseY < photoY || mouseY >= photoY+thePhoto.height) {
            hideTagName();
        }
        };
    
    var tagName = getTagName();
    tagName.onmousemove = thePhoto.onmousemove;
    tagName.onmouseout = thePhoto.onmouseout;

    hideTagName();

    return locator;
}

function disableTagging() {
    last_tag_show = null;

    var thePhoto = $('thePhoto');
    thePhoto.onclick = null;
    thePhoto.onmousemove = null;
    thePhoto.onmouseout = null;
    thePhoto.onmouseover = null;
    thePhoto.style.cursor = '';

    var locator = getLocator();
    locator.onclick = null;
    locator.style.cursor = '';

    hideLocator();
    hideSelector();
    hideTagName();
    var tagName = getTagName();
    tagName.onmousemove = null;
}

function hideTagging() {
    hideLocator();
    hideSelector();
}

function positionLocator(fX, fY) {
    var thePhoto = $('thePhoto');
    if (!thePhoto) return;

    var locator = getLocator();

    photoX = findPosX(thePhoto) + img_border_offset;
    photoY = findPosY(thePhoto) + img_border_offset;

    x = photoX + (fX * thePhoto.width) - (locator_size/2) - locator_border_width;
    y = photoY + (fY * thePhoto.height) - (locator_size/2) - locator_border_width;

    // do a limit check
    minX = photoX-(locator_border_width+locator_inner_border_width);
    minY = photoY-(locator_border_width+locator_inner_border_width);
    if (x < minX && locator_size < thePhoto.width) x = minX;
    if (y < minY && locator_size < thePhoto.height) y = minY;
    
    maxX = photoX+thePhoto.width-locator_size-locator_inner_border_width;
    maxY = photoY+thePhoto.height-locator_size-locator_inner_border_width;
    if (x > maxX && locator_size < thePhoto.width) x = maxX;
    if (y > maxY && locator_size < thePhoto.height) y = maxY;

    return {'x':x, 'y':y};
}

function showLocator(fX, fY) {
    var position = positionLocator(fX, fY);
    if (!position) return;

    var locator = getLocator();
    locator.style.display = '';

    // show it
    locator.style.left = position['x'] + 'px';
    locator.style.top = position['y'] + 'px';
}

function hideLocator() {
    var locator = $('locator');
    if (locator) {
        locator.style.display = 'none';
    }
}

function showSelector(fX, fY, locatorX, locatorY) {
    var thePhoto = $('thePhoto');
    if (!thePhoto) return;

    var selector = getSelector(fX, fY);
    selector.style.display = '';
    $('selector_input_text').focus();
    
    if (userfriend!="")
    {
//            alert(userfriendlist+"1111");
        $('selector_results').innerHTML =userfriend;
    }
    photoX = findPosX(thePhoto) + img_border_offset;
    photoY = findPosY(thePhoto) + img_border_offset;

    if ((locatorX+(locator_size/2)) > (photoX + (thePhoto.width/2)) ) {
        selector.style.left = (locatorX - selector.offsetWidth - 11) + 'px';
    } else {
        selector.style.left = (locatorX + locator_size + locator_border_width + 15) + 'px';
    }
    selector.style.top = (locatorY) + 'px';
}

function hideSelector() {
    var selector = $('selector');
    if (selector) {
        selector.style.display = 'none';
        $('selector_input_text').blur();
        $('selector_input_text').value = '';
        $('selector_results').innerHTML = '';
    }
}

var selectorSearchIndex = 0;
function selectorSearch(input,event) {
    // grab this as early as possible
//    var searchIndex = selectorSearchIndex++;
    if(window.event) {// IE
        keynum = event.keyCode;
    } else if(event.which) {// Netscape/Firefox/Opera
        keynum = event.which;
    }
    
    if (keynum == 27) {
        hideTagging();
        return false;
    } else if (keynum == 13) {
        submitTag();
        return false;
    }
    getphotousers( $('selector_input_text').value);
//    loadJSON('ajax_media_tag_search.php?tag_search=' + $('selector_input_text').value, function(result) {selectorSearchCallback(searchIndex, result)});
}

//var seenIndex = -1;
function selectorSearchCallback(index, result) {
//    if (index > seenIndex) {
//        seenIndex = index;
        var result_search = $('selector_results');
        result_search.innerHTML = (result != null) ? result : "";
//    }
}

function showTagName(index) {
    var tag = tags[index];
    name = tag['name'];
    fX = tag['fX'];
    fY = tag['fY'];
    var tagName = getTagName();

    if (tag['id'] == last_tag_show) {
        tagName.style.display = '';
        return;
    } else last_tag_show = tag['id'];

    var position = positionLocator(fX, fY);
    if (!position) return;

    tagInfo = childWithID(tagName, 'tag_info');
    if (tag['photo_url']) {
        tagInfo.innerHTML = "<img style='float:left; padding-right:5px;' src='" + tag['photo_url'] + "' width='"+user_img_width+"'	height='"+user_img_width+"' /> " + name + "<DIV class='clear'></DIV>";
    } else {
        tagInfo.innerHTML = name;
    }

    tagName.style.left = (position['x'] + locator_border_width + locator_inner_border_width - tag_name_border_width) + 'px';
    tagName.style.top = (position['y'] + locator_border_width + locator_inner_border_width - tag_name_border_width) + 'px';

    var thePhoto = $('thePhoto');
    if (thePhoto.onclick != null) {
        tagName.onclick = thePhoto.onclick;
        tagName.style.cursor = 'crosshair';
    } else {
        tagName.onclick = function() {
            document.location.href = tag['url'];
            return false;
        };
        tagName.style.cursor = 'pointer';
    }
    tagName.style.display = '';
    hideLocator();
}

function hideTagName() {
    var tagName = getTagName();
    if (tagName) {
        tagName.style.display = 'none';
    }
}

var tagSearchCount = 0;
function findShowTagName(event) {
    // don't do work everytime....it just eats up the CPU on the client.
    tagSearchCount++;
    if (tagSearchCount % 5 != 0) return;

    var locator = $('locator');
    if (locator && locator.style.display != 'none') return;

    if (!tags) return;

    mouseX = findMouseX(event);
    mouseY = findMouseY(event);

    var tagIndex = -1;
    min = -1;
    var thePhoto = $('thePhoto');
    photoX = findPosX(thePhoto) + img_border_offset;
    photoY = findPosY(thePhoto) + img_border_offset;

    for (var i=0; i<tags.length; i++) {
        if (!tags[i]) continue;
        var position = positionLocator(tags[i]['fX'], tags[i]['fY']);

        if (mouseX > position['x'] && mouseX < (position['x']+locator_size+locator_border_width) &&
            mouseY > position['y'] && mouseY < (position['y']+locator_size+locator_border_width)) {

            x = photoX + (tags[i]['fX'] * thePhoto.width);
            y = photoY + (tags[i]['fY'] * thePhoto.height);

            diffX = mouseX-x;
            diffY = mouseY-y;
            d2 = diffX*diffX + diffY*diffY;
            if (min == -1 || d2 < min) {
                min = d2;
                tagIndex = i;
            }
        }
    }

    if (tagIndex != -1) showTagName(tagIndex);
    else hideTagName();

    hideLocator();
}

function submitTag() {
    var form = $('selector_form');
    var tagword=getFormField(form, 'tag');
    var radiochecked = jointeRadioChecked($('selector_form'),'user_id');
    if (tagword.value!="" ||radiochecked)
    {
    }
    else 
    {
        return;
    }
    var email = getFormField(form, 'email');
    if (email && email.value && !email.value.match( /[\w\.\+\-=]+@[\w\.\-]+\.[\w\-]+/ )) {
        alert('email格式不正确，请重试!');
    } else {
        if ($('tagging_status_internal')) $('tagging_status_internal').innerHTML = "<CENTER><IMG src='/images/photoTag/processing.gif'/></CENTER>";
//        loadJSON('ajax_media_tag_search.php', tagUpdateCallback, getFormParameters($('selector_form')));
addphototags();
        hideTagging();
    }
}

function deleteTag(tag_id) {
    hideTagName();
    var answer = confirm("你确定要删除此标签吗？");
    if (answer) {
        if ($('tagging_status_internal')) $('tagging_status_internal').innerHTML = "<CENTER><IMG src='/images/photoTag/processing.gif'/></CENTER>";
        delphototags(tag_id);
//        loadJSON('ajax_media_tag_search.php', tagUpdateCallback, "_submit_check=delete_tag&entitymedia_id=" + entitymedia_id + "&id=" + tag_id);
        hideTagging();

    }
}

//function tagUpdateCallback(result) {
//    if (result['error_code'] > 0) tags = result['tags'];
//    tags=null;
//    tags['name']='hshiliang'
//    tags['fX']=10;
//    fY = 20;;
//    if (result['messages'] && $('tagging_status_internal')) $('tagging_status_internal').innerHTML = result['messages'].join("<br/>");

//    displayTags();
//}


function displayTags() {
    var tags_area = $('tags_area');
    tags_area.style.display = '';

    var tags_list = $('tags_list');
    tags_list.innerHTML = "";

    if (!tags || tags.length == 0) {
        tags_area.style.display = 'none';
        return;
    }
    for (var i=0; i<tags.length; i++) {
        var tag = tags[i];
        if (!tag) continue;

        if (i != 0) {
            tags_list.innerHTML += '&nbsp;| ';
        }
        tags_list.innerHTML += "<SPAN onmouseover='hideTagging(); showTagName(" + i + ");' onmouseout='hideTagName();'><a href='"+tag['url']+"' target=\"_blank\">" + tag['name'] + "</a>" + (tag['remove'].indexOf("True")>-1 ? " (<a href='#' onclick='deleteTag(" + tag['id'] + "); return false;'>删除</a>)" : '')+"</SPAN>";

    }
}



//var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//var base64DecodeChars = new Array(    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);//客户端Base64编码
//function base64encode(str) {    
//var out, i, len;    
//var c1, c2, c3;
//    len = str.length;    
//    i = 0;    
//    out = "";    
//    while(i < len) 
//    { 
//    c1 = str.charCodeAt(i++) & 0xff; 
//    if(i == len)
//     {     
//     out += base64EncodeChars.charAt(c1 >> 2);     
//     out += base64EncodeChars.charAt((c1 & 0x3) << 4);     
//     out += "==";     
//     break; }
//      c2 = str.charCodeAt(i++); 
//      if(i == len) 
//      {     
//      out += base64EncodeChars.charAt(c1 >> 2);     
//      out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));    
//       out += base64EncodeChars.charAt((c2 & 0xF) << 2);     
//       out += "=";     
//       break; 
//       } 
//       c3 = str.charCodeAt(i++); 
//       out += base64EncodeChars.charAt(c1 >> 2); 
//       out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4)); 
//       out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)); 
//       out += base64EncodeChars.charAt(c3 & 0x3F);    
//       }    
//       return out;
//       }
